如果ToDate等于第二个FromDate SQL Server,则合并两个记录日期?

时间:2016-07-12 09:40:13

标签: sql sql-server

示例数据:

FK_EmployeeId   FromDate                  ToDate                      DateDiff
20325           2016-06-24 00:00:00.000   2016-06-25 00:00:00.000     2
20325           2016-06-25 00:00:00.000   2016-06-26 00:00:00.000     2
20325           2016-06-26 00:00:00.000   2016-06-28 00:00:00.000     3
20325           2016-06-28 00:00:00.000   2016-06-29 00:00:00.000     2
20325           2016-06-29 00:00:00.000   2016-06-30 00:00:00.000     2
20325           2016-06-30 00:00:00.000   2016-07-01 00:00:00.000     2
20325           2016-07-01 00:00:00.000   2016-07-02 00:00:00.000     2
20325           2016-07-02 00:00:00.000   2016-07-03 00:00:00.000     2
20325           2016-07-03 00:00:00.000   2016-07-04 00:00:00.000     2
20325           2016-07-04 00:00:00.000   2016-07-05 00:00:00.000     2

我想得到以下输出:

FK_EmployeeId   FromDate                  ToDate                      DateDiff
20325           2016-06-24 00:00:00.000   2016-06-26 00:00:00.000     3
20325           2016-06-28 00:00:00.000   2016-07-05 00:00:00.000     8

1 个答案:

答案 0 :(得分:1)

我认为您正尝试使用窗口函数将以下内容连接到自身以执行2行的日期比较。

然而,正如人们已经在评论中建议的那样,您上面的示例数据包含所有连续日期,因此不太清楚您期望它如何工作。因此,我在样本数据中排除了一个中间值,以证明该方法。

--TABLE JUST FOR EXAMPLE QUERY
DECLARE @SomeTable TABLE ([FK_EmployeeId] INT,[FromDate] DATETIME,[ToDate] DATETIME,[DateDiff] INT)

--YOUR SAMPLE DATA
INSERT INTO @SomeTable 
    ([FK_EmployeeId],[FromDate],[ToDate],[DateDiff])
SELECT 20325,'2016-06-24 00:00:00.000','2016-06-25 00:00:00.000',2
UNION SELECT 20325,'2016-06-25 00:00:00.000','2016-06-26 00:00:00.000',2
UNION SELECT 20325,'2016-06-26 00:00:00.000','2016-06-28 00:00:00.000',3
UNION SELECT 20325,'2016-06-28 00:00:00.000','2016-06-29 00:00:00.000',2
UNION SELECT 20325,'2016-06-29 00:00:00.000','2016-06-30 00:00:00.000',2
--UNION SELECT 20325,'2016-06-30 00:00:00.000','2016-07-01 00:00:00.000',2 --<<
UNION SELECT 20325,'2016-07-01 00:00:00.000','2016-07-02 00:00:00.000',2
UNION SELECT 20325,'2016-07-02 00:00:00.000','2016-07-03 00:00:00.000',2
UNION SELECT 20325,'2016-07-03 00:00:00.000','2016-07-04 00:00:00.000',2
UNION SELECT 20325,'2016-07-04 00:00:00.000','2016-07-05 00:00:00.000',2

--THE POINT:
;WITH cte AS
    (
    SELECT 
        *,
        ROW_NUMBER() OVER (PARTITION BY [FK_EmployeeId] ORDER BY [ToDate]) AS 'RowNo'
    FROM 
        @SomeTable
    )

SELECT
    a.*,
    DATEDIFF(DAY,a.[FromDate],b.[ToDate]) AS 'NewDiff'
FROM
    cte a
    JOIN cte b
        ON a.[RowNo] + 1 = b.[RowNo]
WHERE
    a.[ToDate] <> b.[FromDate]

请问下一次问题的更多细节。