为空行获取以前的值

时间:2015-01-20 22:51:20

标签: mysql

如果下一行为空,有没有办法让我获得前一个值? 我的数据库看起来像这样

|           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 |

目前我唯一的查询只是得到最后一行12.2和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

我想要的输出是

如果我使用它,我得到的结果是

|           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 |

我有办法让这个工作吗?

谢谢。

2 个答案:

答案 0 :(得分:2)

select
    tstamp,
    if(val1 is null,@prevVal1,@prevVal1:=val1),
    if(val2 is null,@prevVal2,@prevVal2:=val2)
from t;

:=运算符为变量赋值并返回该值。

答案 1 :(得分:0)

改编atxdba的优秀解决方案......

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;