在第一个null之前找到行



我有一个与此

相似的表格
timestamp              val
2017-05-04 06:00:00      2
2017-05-04 08:00:00      3
2017-05-04 09:35:00      5
2017-05-04 10:05:00      
2017-05-04 11:15:00      8
2017-05-04 12:10:00      
2017-05-04 13:35:00     12

我想在val字段中的第一个零之前找到记录(示例表中的时间戳为09:35(。

有一个简单的方法吗?

谢谢

编辑:使用Postgres 9.5EDIT2:对不起,我忘了提到有时没有空的每个人,在这种情况下,我只需要最大的时间戳即可。到目前为止提供的答案在这种情况下尚未起作用(对原始问题中的松散解释再次抱歉(

LEAD((函数使用特定顺序返回分区的下一个值。

如果没有零值,此解决方案将返回最后一个记录。

with lg as
(
    select tm, val, 
           lead(val) over (order by tm) next_val
    from   your_table
)
select   tm as "timestamp", val
from     lg
where    next_val is null
order by tm
limit 1;
时间戳|瓦尔:----------------------- | - :2017-05-04 09:35:00 |5

dbfiddle在这里

hmmm。。。

select t.*
from t
where t.timestamp < (select min(t2.timestamp) from t t2 where t2.val is null)
order by t.timestamp desc
limit 1;

如果不是null值,它将返回第一个空值的记录上方的最后一行。

select t.*
from t
where  t.timestamp <= (select min(t2.timestamp) 
                        from NAMEs t2 
                        where (t2.val is null or t2.timestamp = (select max(timestamp) from NAMES) ) 
                )
        and t2.val is not null        
order by t.timestamp desc
limit 1 ;

最新更新