我们如何选择48小时内出现多次的记录计数?
例如
ID DATE
1 9/24/2018
1 9/23/2018
1 9/20/2018
2 9/20/2018
ID 1在48小时内的出现次数超过一次
请让我知道如何编写一个sql查询来做到这一点
答案 0 :(得分:2)
有很多方法,但我将从使用LAG()
和日期比较开始。假设您的DATE列是日期数据类型?
WITH
entity_summary AS
(
SELECT
ID,
CASE
WHEN LAG("DATE") OVER (PARTITION BY ID ORDER BY "DATE") >= "DATE" - INTERVAL '2' DAY
THEN 1
ELSE 0
END
AS occurence_within_2_day
FROM
Table1
)
SELECT
ID,
SUM(occurence_within_2_day)
FROM
entity_summary
GROUP BY
ID
HAVING
SUM(occurence_within_2_day) >= 1