我有一个TmLeave表,结构如下:
EmployeeID StartDate EndDate LeaveDuration ------------------------------------------------------ 0001 20/07/2014 20/07/2014 1 0001 21/07/2014 21/07/2014 1 0001 22/07/2014 22/07/2014 1 0001 24/07/2014 25/07/2014 2 0001 26/07/2014 26/07/2014 1 0001 28/07/2014 30/07/2014 3
我想计算员工连续几天的LeaveDuration值总和,我的结果集应如下所示:
EmployeeID StartDate EndDate LeaveDuration ------------------------------------------------------ 0001 20/07/2014 22/07/2014 3 0001 24/07/2014 26/07/2014 3 0001 28/07/2014 30/07/2014 3
答案 0 :(得分:1)
请使用CTE
检查以下答案:
;With T as (
select
ROW_NUMBER() over(partition by a.EmployeeID order by a.StartDate) RN,
*
From tbl a
)
,T1 as (
select
*,
RN CN
from T
where RN=1
union all
select
T.*,
case when T1.EndDate+1=T.StartDate then CN else T.RN end
from T join T1 on T.RN=T1.RN+1
)
select
EmployeeID,
MIN(StartDate) StartDate,
MAX(EndDate) EndDate,
SUM(LeaveDuration) LeaveDuration
from T1
group by EmployeeID, CN