为 SQL 中连续几小时的组赋予共同值

Giving a common value to groups of consecutive hours in SQL

我正在使用 Netezza。

假设我有一个包含两个字段的 table:一个字段是与一天中的每个小时相对应的时间戳,另一个是患者是否在一小时内服用抗酸剂的指标。 table 如下所示:

Timestamp           Antacid?
11/23/2016 08:00          1
11/23/2016 09:00          1
11/23/2016 10:00          1
11/23/2016 11:00          0
11/23/2016 12:00          0
11/23/2016 13:00          1
11/23/2016 14:00          1
11/23/2016 15:00          0

有没有办法为每组连续的小时间隔分配一个公共分区值?像这样...

Timestamp           Antacid?      Group
11/23/2016 08:00          1           1
11/23/2016 09:00          1           1
11/23/2016 10:00          1           1
11/23/2016 11:00          0        NULL
11/23/2016 12:00          0        NULL
11/23/2016 13:00          1           2
11/23/2016 14:00          1           2
11/23/2016 15:00          0        NULL

我最终想计算出所有连续使用抗酸剂小时的开始日期和结束日期(因此第一组的开始和结束日期为 11/23/2016 08:00 和 11 /23/2016 10:00,第二组的 start/end 日期分别为 11/23/2016 13:00 和 11/23/2016 14:00)。我之前连续几天使用 extract(epoch from date - row_number()) 完成了此操作,但我不确定如何处理时间。

我假设必须为每位患者完成此操作(此处查询中的 id)。您可以使用

select id,antacid,min(dt) startdate,max(dt) enddate from (
select t.*,
-row_number() over(partition by id,antacid order by dt) 
+ row_number() over(partition by id order by dt) grp
from t
) x
where antacid = 1
group by id,antacid,grp
order by 1,3

内部查询为给定的患者 ID 获取连续的 0 和 1 抗酸剂组。因为你只需要 antacid=1 的开始和结束日期,所以你可以使用 where 子句来过滤。

如果每天都必须按日期添加分区。

编辑:仅当当前行与下一行之间相差一个小时时才对行进行分组。

select id,antacid,min(dt) startdate,max(dt) enddate from (
select t.*,
--change dateadd as per Netezza functions so you add -row_number hours
dateadd(hour,-row_number() over(partition by id,antacid order by dt),dt) grp
from t
) x
where antacid = 1
group by id,antacid,grp
order by 1,3