Get previous value for zero rows

Is there a way to get the previous value if the next line is zero? My database is as follows

| tstamp | val1 | val2 | | 2015-01-21 01:00:00 | 15.2 | 25.1 | | 2015-01-21 01:30:00 | null | null | | 2015-01-21 02:00:00 | null | 14.1 | | 2015-01-21 02:30:00 | 11.2 | null | | 2015-01-21 03:00:00 | null | 21.1 | | 2015-01-21 03:30:00 | 12.2 | 13.1 | 

Currently, the only request I get is only the last line, which is 12.2 and 13.1

 SELECT tstamp, val1, val2 FROM table WHERE id IN (1,2) AND tstamp BETWEEN "2015-01-21 00:00:00" AND "2015-01-21 23:00:00" GROUP BY DATE(tstamp), HOUR(tstamp), MINUTE(tstamp) DIV 30 ORDER BY tstamp DESC LIMIT 1 

My desired result

If I use this result, I get

 | tstamp | val1 | val2 | | 2015-01-21 01:00:00 | 15.2 | 25.1 | | 2015-01-21 01:30:00 | 15.2 | 25.1 | | 2015-01-21 02:00:00 | 15.2 | 14.1 | | 2015-01-21 02:30:00 | 11.2 | 14.1 | | 2015-01-21 03:00:00 | 11.2 | 21.1 | | 2015-01-21 03:30:00 | 12.2 | 13.1 | 

Is there any way to make this work?

Thanks.

+1
source share
2 answers
 select tstamp, if(val1 is null,@prevVal1,@prevVal1:=val1), if(val2 is null,@prevVal2,@prevVal2:=val2) from t; 

The: operator: assigns a value to a variable, and also returns that value.

+2
source

Adapting atxdba is otherwise a great solution ...

 SELECT tstamp , IF(val1 is null,@prevVal1,@prevVal1:=val1) , if(val2 is null,@prevVal2,@prevVal2:=val2) from my_table , (SELECT @preVal1:=null,@preVal2:=null) vars ORDER BY tstamp; 
0
source

Source: https://habr.com/ru/post/894935/


All Articles