过滤在5分钟内发生的时间戳。

时间:2017-11-09 03:04:16

标签: sql postgresql

我试图找到在过去五分钟内完成的样本的葡萄糖结果并将其过滤掉。下面是我的PostgreSQL代码及其输出。

SELECT date
       , blood_glucose
       , extract(epoch from date - lag(date) OVER(ORDER BY date))/60 
FROM glucose
ORDER BY DATE


date               |glucose|minutes since last    
----------------------------------------------
2017-10-02 08:05:00|183    |681
2017-10-04 08:19:00|275    |2894
2017-10-05 08:03:00|273    |1424
2017-10-05 08:03:00|294    |0
2017-10-05 08:04:00|277    |1
2017-10-05 18:19:00|187    |615
2017-10-09 21:26:00|190    |5947

我试图得到一个结果:

date               |glucose|minutes since last    
----------------------------------------------
2017-10-05 08:03:00|273    |1424
2017-10-05 08:03:00|294    |0
2017-10-05 08:04:00|277    |1

我希望在5分钟内完成所有测试。在这种情况下,我不知道如何能够包含第一行葡萄糖水平为273的第一行。

2 个答案:

答案 0 :(得分:1)

这下面的sql会生成三行,我认为这就是你想要的。它返回在5分钟内发生先前记录的任何记录,或在5分钟内发生的下一记录。这是针对sqlserver的,所以可能不喜欢和postgresql一样

2017-10-05 08:03:00 294 -1424 0

2017-10-05 08:03:00 273 0 1

2017-10-05 08:04:00 277 -1 615

with dat as
(
select '2017-10-02 08:05:00' t,183 g union all
select '2017-10-04 08:19:00',275 union all
select '2017-10-05 08:03:00',273 union all
select '2017-10-05 08:03:00',294 union all
select '2017-10-05 08:04:00',277 union all
select '2017-10-05 18:19:00',187 union all
select '2017-10-09 21:26:00',190
)
select * from
(
    select dat.t,
           g,
           datediff(mi,t,lag (t,1) over (order by t)) timeprev,
           datediff(mi,t,lead (t,1) over (order by t)) timenext
    from   dat
) x
where timeprev >=-5 or timenext <=5

答案 1 :(得分:-1)

您似乎想要具有多个元素的序列,其中任何两个相邻元素之间的差异小于5.

您可以使用with g as ( select g.*, extract(epoch from date - lag(date) over (order by date)) / 60 as minutes_since_last from glucose g ), gg as ( select g.*, sum( (minutes_since_last <= 5)::int) over (order by date) as grp from g ), ggg as ( select gg.*, count(*) over (partition by grp) as cnt from gg ) select ggg.* from ggg where cnt > 1 order by date; 来识别序列的起始位置,然后使用累积和来识别序列,最后使用窗口函数来确定序列的长度。

$d1 = "00:45:00";
$d2 = "00:00:50";

date_default_timezone_set("utc");

$fakedate = '01/01/2017';

$d1 = $fakedate . ' ' . $d1;
$d2 = $fakedate . ' ' . $d2;

$dt1 = new DateTime($d1);
$dt2 = new DateTime($d2);


$diff = $dt1->diff($dt2);

echo $diff->format("%H:%I:%S");