SQL Window 函数,以每个事件日期为索引统计 180 天内发生的事件数 window

SQL Window function, count the number of events in a 180 day window using each event date as an index

我需要能够从一组符合以下条件的日期中找出最短的日期。

3 个日期,彼此相隔 180 天以内。我猜想适用的逻辑是每个日期都是一个索引,后续日期将与该索引进行比较。如果有两个日期,我可以使用 LAG 和 Window 函数来执行此操作。但要求是找到 3 个事件适合 180 天 window 并按 GROUP_ID.

分组的最短日期

测试数据为:

DROP TABLE #EVENT_COUNT
CREATE TABLE #EVENT_COUNT
(
    [DATE]    DATE 
    ,[GROUP_ID]    INT 

);

INSERT INTO #EVENT_COUNT
SELECT '2011-01-01',1
UNION ALL SELECT '2011-02-01',1 UNION ALL SELECT '2011-03-01',1
UNION ALL SELECT '2011-04-01',1 UNION ALL SELECT '2011-05-01',1
UNION ALL SELECT '2011-06-01',1 UNION ALL SELECT '2011-07-01',1
UNION ALL SELECT '2011-08-01',1 UNION ALL SELECT '2011-09-01',1
UNION ALL SELECT '2011-10-01',1 UNION ALL SELECT '2011-11-01',1
UNION ALL SELECT '2011-12-01',2 UNION ALL SELECT '2012-01-01',2
UNION ALL SELECT '2012-02-01',2 UNION ALL SELECT '2012-03-01',2
UNION ALL SELECT '2012-04-01',2 UNION ALL SELECT '2012-05-01',2
UNION ALL SELECT '2012-06-01',2 UNION ALL SELECT '2012-07-01',2
UNION ALL SELECT '2012-08-01',2 UNION ALL SELECT '2012-09-01',2
UNION ALL SELECT '2012-10-01',2 UNION ALL SELECT '2012-11-01',2
UNION ALL SELECT '2012-12-01',2;

SELECT * FROM #EVENT_COUNT;

这是创建的table:

 DATE       |GROUP_ID
    ---------------------
    2011-01-01  |1<<This date
    2011-02-01  |1
    2011-03-01  |1
    2011-04-01  |1
    2011-05-01  |1
    2011-06-01  |1
    2011-07-01  |1
    2011-08-01  |1
    2011-09-01  |1
    2011-10-01  |1
    2011-11-01  |1
    2011-12-01  |2 << This date
    2012-01-01  |2
    2012-02-01  |2
    2012-03-01  |2
    2012-04-01  |2
    2012-05-01  |2
    2012-06-01  |2
    2012-07-01  |2
    2012-08-01  |2
    2012-09-01  |2
    2012-10-01  |2
    2012-11-01  |2
    2012-12-01  |2

我需要的结果是按 GROUP_ID:

分组的两个粗体日期
DATE        |GROUP_ID
---------------------
2011-01-01  |1<<This date
2011-12-01  |2 << This date

非常感谢任何帮助。

您可以使用 LEAD 函数并查看当前日期的下一个日期来执行此操作。如果相差小于180,就满足你的条件:

SELECT a.Group_ID,min(Date) as Date
FROM
(SELECT *,
       lead(date,2) over(partition by group_id order by date) as lag_date2 
FROM #EVENT_COUNT) a
WHERE DATEDIFF(day,date,ISNULL(lag_date2,'01Jan2100'))<=180
GROUP BY a.Group_ID

希望对您有所帮助。