SQL Date Diff计算大日期列表

时间:2018-05-15 14:34:01

标签: sql sql-server datediff

我正在尝试根据日期对记录集进行计数,但是我试图将它拉到一起。

以下面的表1为例,我想采取最早的日期,然后采取不是在此日期的七天之内的下一个日期,并重复。从下面的表1可以看出,这将有效地给出4'第一日期',04 / 01,12 / 01,27 / 01和07/02。基本上创建一个'FirstDate'记录表,以便与

连接更多表

目的是在“第一次约会”的7天,30天,60天和90天内记录此视图。 (30天计算将返回2'FirstDate'记录,04/01/201和07/02/2018)

我从一个Date和ID表开始,并以Date ID和MinDate结束。

Table 1
    Date         ID      MinDate
    04/01/2018  12345   04/01/2018
    05/01/2018  12345   NULL
    10/01/2018  12345   NULL
    12/01/2018  12345   12/01/2018
    14/01/2018  12345   NULL
    15/01/2018  12345   NULL
    18/01/2018  12345   NULL
    27/01/2018  12345   27/01/2018
    28/01/2018  12345   NULL
    31/01/2018  12345   NULL
    01/02/2018  12345   NULL
    02/02/2018  12345   NULL
    07/02/2018  12345   07/02/2018
    08/02/2018  12345   NULL
    09/02/2018  12345   NULL

非常感谢任何帮助

由于

1 个答案:

答案 0 :(得分:0)

您可以使用递归CTE执行此操作。锚是表的最小日期,递归与所有记录连接,并且具有参数化的天数差异。最后按递归级别分组(递归CTE不允许聚合)并找到最小日期。

IF OBJECT_ID('tempdb..#Dates') IS NOT NULL
    DROP TABLE #Dates

CREATE TABLE #Dates (
    YourDate DATE,
    GroupID INT)

INSERT INTO #Dates (
    YourDate,
    GroupID)
VALUES
    ('2018/01/04', 1),
    ('2018/01/05', 2),
    ('2018/01/10', 1),
    ('2018/01/12', 2),
    ('2018/01/14', 1),
    ('2018/01/15', 2),
    ('2018/01/18', 1),
    ('2018/01/27', 2),
    ('2018/01/28', 1),
    ('2018/01/31', 2),
    ('2018/02/01', 1),
    ('2018/02/02', 2),
    ('2018/02/07', 1),
    ('2018/02/08', 2),
    ('2018/02/09', 1)

DECLARE @MinimumDayDifference INT = 7

;WITH RecursiveDaysDifferences AS 
(
    SELECT
        GroupID = D.GroupID,
        SelectedDate = MIN(D.YourDate),
        Level = 0
    FROM
        #Dates AS D
    GROUP BY
        D.GroupID

    UNION ALL

    SELECT
        GroupID = C.GroupID,
        SelectedDate = D.YourDate,
        Level = C.Level + 1
    FROM
        RecursiveDaysDifferences AS C
        INNER JOIN #Dates AS D ON 
            C.GroupID = D.GroupID AND
            D.YourDate >= DATEADD(DAY, @MinimumDayDifference, C.SelectedDate)
)
SELECT
    GroupID = C.GroupID,
    SelectedDate = MIN(C.SelectedDate)
FROM
    RecursiveDaysDifferences AS C
GROUP BY
    C.GroupID,
    C.Level
ORDER BY
    C.GroupID,
    C.Level
OPTION
    (MAXRECURSION 2000)

日差7的结果:

GroupID SelectedDate
1   2018-01-04
1   2018-01-14
1   2018-01-28
1   2018-02-07
2   2018-01-05
2   2018-01-12
2   2018-01-27
2   2018-02-08

日差30的结果:

GroupID SelectedDate
1   2018-01-04
1   2018-02-07
2   2018-01-05
2   2018-02-08

如果您有数千个日期,则递归连接将升级为非常多的行(即使我们最后只显示其中的一些)。在这种情况下,您可能希望稍微调整一下连接逻辑。