我有一个数据表,其中单个连续记录可能有多个条目。
Empno StartDate EndDate Wdays
1 2014-07-23 2014-07-23 1
1 2014-11-07 2014-11-29 15
1 2014-11-30 2014-12-07 8
1 2014-12-08 2014-12-19 11
2 2014-11-15 2014-11-16 2
如果开始日期在同一个empno的结束日期之后,我希望只显示一条记录,如下所示。
Empno StartDate EndDate Wdays
1 2014-07-23 2014-07-23 1
1 2014-07-23 2014-12-19 34
2 2014-11-15 2014-11-16 2
我已经用下面显示的答案解决了日期问题,但是任何人都可以帮我总结每个实例的“Wdays”
答案 0 :(得分:2)
select empno,
min(startdate) as startdate,
max(enddate) as enddate
from your_table
group by empno
答案 1 :(得分:0)
感谢那些发布到我原始查询的人,如果我不清楚我遇到的问题,我会道歉。以下是问题如何解决我通过使用答案" ypercube" (https://stackoverflow.com/users/344949/ypercube)发布于2012年
With StartData As
( Select
, empno
, startdate
, enddate
, desc
, wdays
From
Mytable
)
,
StartD AS
( SELECT
Empno
, startdate
, ROW_NUMBER() OVER( PARTITION BY Empno ORDER BY startdate )
AS Rn
FROM
StartData AS t
WHERE
NOT EXISTS
( SELECT *
FROM StartData AS p
WHERE p.empno = t.empno
AND p.startdate < t.startdate
AND t.startdate <= DATEADD(day, 1, p.EndDate)
)
)
, EndD AS
( SELECT
empno
, EndDate
, ROW_NUMBER() OVER( PARTITION BY empno ORDER BY EndDate )
AS Rn
FROM
StartData AS t
WHERE
NOT EXISTS
( SELECT *
FROM StartData AS p
WHERE p.empno = t.empno
AND DATEADD(day, -1, p.startdate) <= t.EndDate
AND t.EndDate < p.EndDate
)
)
SELECT
s.empno
, s.startdate
, e.EndDate
FROM
StartD AS s
JOIN
EndD AS e
ON e.empno = s.empno
AND e.Rn = s.Rn