Perform line offset(lead Function) by making the last line 0 instead of 'NULL'

Asked

Viewed 20 times

0

I’m using correlated subsettes to simulate the LEAD function because my Mysql does not support this function, by scrolling the rows of a column. However, when moving, either through the original LEAD function or the code below that I implemented, the last line has NULL value, making it impossible for me to perform the subtraction operation.

The code is (taken from:https://dba.stackexchange.com/questions/187933/simulate-effective-lead1-or-lead2-in-mysql):

SELECT t1.digit, t2.digit,t1.digit -t2.digit as 'diff'
FROM (
    SELECT digit, @rownum1 := @rownum1 + 1 AS id
    FROM
     alfabet  , (SELECT @rownum1 := 0) r
    ORDER BY
     alfabet.digit ASC
) AS t1
LEFT OUTER JOIN ( 
    SELECT digit, @rownum2 := @rownum2 + 1 AS id
    FROM
     alfabet  , (SELECT @rownum2 := 0) r
    ORDER BY
     alfabet.digit ASC
) AS t2
  ON t1.id +1 = t2.id;

This works perfectly for me, but I have as a result:

digit   next_digit     diff
4       2              2         
2       2              0           
2       2              0          
2       1              1                  
1       NULL           NULL 

I need to make the value of 0 appear in the next_digit column instead of NULL, so that it is possible to subtract and return it to diff (1-0 = 1). Or, some way to subtract with NULL and still return the value 1 in the diff column, some operation that allows to do (1-null = 1).

[RESOLVED]

Using the coalesce function

SELECT t1.name, t1.cnt, t2.cnt_lead, coalesce (t1.cnt - t2.cnt_lead, t1.cnt) as 'diff'
``
  • Function COALESCE()?

  • It worked perfectly. Thank you. If someone needs it, it looks like this SELECT t1.name, t1.cnt, t2.cnt_lead, coalesce (t1.cnt - t2.cnt_lead, t1.cnt) the diff like this, if the subtraction returns null, it keeps the value of the original column.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.