如果员工从1月1日到1月15日连续工作,如何成为1条记录。 请帮帮我
empid datebegin dateend
1 2017-02-01 2017-02-05
1 2017-02-06 2017-02-08
1 2017-02-09 2017-02-15
期望的O / P:1 2017-02-01 2017-02-15
scenario2:没有连续工作
empid datebegin dateend
1 2017-02-01 2017-02-05
1 2017-02-07 2017-02-08
1 2017-02-09 2017-02-15
期望的O / P: empid datebegin dateend
1 2017-02-01 2017-02-05
1 2017-02-07 2017-02-15
答案 0 :(得分:0)
使用MAX和MIN聚合:
CREATE TABLE #Table(empid INT, datebegin DATE , dateend DATE)
INSERT INTO #Table( empid , datebegin , dateend)
SELECT 1,'2017-02-01','2017-02-05' UNION ALL
SELECT 1,'2017-02-06','2017-02-08' UNION ALL
SELECT 1,'2017-02-09','2017-02-15'
SELECT empid , MIN(datebegin) datebegin ,MAX(dateend) dateend
FROM #Table
GROUP BY empid
答案 1 :(得分:0)
使用Common表表达式和ROW_NUmber可以这样做
DECLARE @sample TABLE (empid INT, datebegin DATE, dateend DATE )
INSERT INTO @sample
( empid, datebegin, dateend )
VALUES
(1,'2017-02-01','2017-02-05' )
,(1,'2017-02-06','2017-02-08' )
,(1,'2017-02-09','2017-02-15' )
,(2,'2017-02-01','2017-02-05' )
,(2,'2017-02-07','2017-02-08' )
,(2,'2017-02-09','2017-02-15' )
;WITH cteX
AS(
SELECT
ROW_NUMBER()OVER (ORDER BY S.empid, S.datebegin) 'RN'
, S.empid
, S.datebegin
, S.dateend
FROM @sample S
)
SELECT
S.RN
, S.empid
, S.datebegin
, S.dateend
, DATEDIFF(DAY,S.dateend, S1.datebegin ) 'Diff'
, S1.datebegin
, S1.dateend
FROM cteX S
JOIN
cteX S1 ON S1.empid = S.empid AND S1.RN = S.RN + 1
ORDER BY S.RN
产生以下输出
empid datebegin dateend
1 2017-02-01 2017-02-15
2 2017-02-01 2017-02-05
2 2017-02-07 2017-02-15