Home > Software engineering >  If value is null get the one from before
If value is null get the one from before

Time:04-12

How to get last row's value if current value is null?

I tried using LAG, but it returns null after second row.

SELECT timestamp, min, lag(min) over (order by id asc) as lag
from table

enter image description here

CodePudding user response:

From your description, you can try to SUM window function make a group then use max/min window function.

SELECT `timestamp`, 
     `min`,
      CASE WHEN `min` IS NULL THEN MAX(`min`) OVER(PARTITION BY grp order by id asc)  END
FROM (
    SELECT `timestamp`, 
           `min`, 
           SUM(CASE WHEN `min` IS NOT NULL THEN 1 ELSE 0 END) OVER(order by id asc) grp
    from `table`
) t1

sqlfiddle

  • Related