每个滚动 5 分钟周期的组观察(雪花 SQL)
Observations in Group Per Any Rolling 5 Minute Period (Snowflake SQL)
我有一个包含 2 列的 table,这是一个示例:
ID
DateTime
1
2022-04-01 13:19:15
1
2022-04-01 13:20:19
1
2022-04-01 15:01:37
2
2022-04-01 10:08:21
2
2022-04-01 12:09:32
2
2022-04-01 15:07:25
我正在尝试在 Snowflake 中构建一个 SQL 查询,其中 returns 所有在 ANY 中至少有 2 条或更多记录的 ID滚动 5 分钟 window。对于提供的示例数据,将返回 ID 1,但不会返回 ID 2,因为该 ID 的所有时间间隔都超过 5 分钟。
在尝试寻找此问题的解决方案时,似乎递归 CTE 可能是解决此问题的正确方法,但我似乎无法确切理解如何解决此问题。
如有任何支持或指导,我们将不胜感激!
对数据使用 CTE -
with data_cte (id, date1) as
(
select * from values
(1,'2022-04-01 13:19:15'::timestamp),
(1,'2022-04-01 13:20:19'::timestamp),
(1,'2022-04-01 15:01:37'::timestamp),
(2,'2022-04-01 10:08:21'::timestamp),
(2,'2022-04-01 12:09:32'::timestamp),
(2,'2022-04-01 15:07:25'::timestamp)
), twindow_cte as (
select
id,
nvl(
TIMESTAMPDIFF('minute',date1,
lead(date1) over (partition by id order by null)), 0) tdiff from
data_cte)
select distinct id from twindow_cte a where
1< (select count(*) from twindow_cte b
where b.tdiff <=5 and b.id = a.id);
ID
1
我有一个包含 2 列的 table,这是一个示例:
ID | DateTime |
---|---|
1 | 2022-04-01 13:19:15 |
1 | 2022-04-01 13:20:19 |
1 | 2022-04-01 15:01:37 |
2 | 2022-04-01 10:08:21 |
2 | 2022-04-01 12:09:32 |
2 | 2022-04-01 15:07:25 |
我正在尝试在 Snowflake 中构建一个 SQL 查询,其中 returns 所有在 ANY 中至少有 2 条或更多记录的 ID滚动 5 分钟 window。对于提供的示例数据,将返回 ID 1,但不会返回 ID 2,因为该 ID 的所有时间间隔都超过 5 分钟。
在尝试寻找此问题的解决方案时,似乎递归 CTE 可能是解决此问题的正确方法,但我似乎无法确切理解如何解决此问题。
如有任何支持或指导,我们将不胜感激!
对数据使用 CTE -
with data_cte (id, date1) as
(
select * from values
(1,'2022-04-01 13:19:15'::timestamp),
(1,'2022-04-01 13:20:19'::timestamp),
(1,'2022-04-01 15:01:37'::timestamp),
(2,'2022-04-01 10:08:21'::timestamp),
(2,'2022-04-01 12:09:32'::timestamp),
(2,'2022-04-01 15:07:25'::timestamp)
), twindow_cte as (
select
id,
nvl(
TIMESTAMPDIFF('minute',date1,
lead(date1) over (partition by id order by null)), 0) tdiff from
data_cte)
select distinct id from twindow_cte a where
1< (select count(*) from twindow_cte b
where b.tdiff <=5 and b.id = a.id);
ID |
---|
1 |