2014-09-23 142 views
0

我有这样的数据: tb_Leave计数总交易与日期范围

id | empID | startDate | endDate 
1 |  1  | 01/02/2014 | 01/05/2014  ------ 2, 3, 4, 5 
2 |  2  | 01/03/2014 | 01/03/2014  ------ 3 
3 |  3  | 01/04/2014 | 01/07/2014  ------ 4, 5, 6, 7 
4 |  4  | 01/03/2014 | 01/07/2014  ------ 3, 4, 5, 6, 7 
5 |  5  | 01/09/2014 | 01/09/2014  ------ 9 

我想在一个特定的天,返回所有总休假。 出来放:

total | Date 
    1  | 01/02/2014 
    3  | 01/03/2014 
    3  | 01/04/2014 
    3  | 01/05/2014 
    2  | 01/06/2014 
    2  | 01/07/2014 
    1  | 01/09/2014 
+0

是否必须是单个查询? – 2014-09-23 02:09:11

+0

任何种类的查询。 – user2530833 2014-09-23 02:12:35

回答

1

可以扩大使用递归CTE的日期,然后使用group by

with cte as (
     select startdate as thedate, enddate 
     from tb_leave 
     union all 
     select dateadd(day, 1, startdate), enddate 
     from cte 
     where startdate < enddate 
) 
select thedate, count(*) 
from cte 
group by thedate 
with (MAXRECURSION 0); 

注:这是假定有不超过99天一行。否则,请添加一个MAXRECURSION选项。您也可以通过加入数字表来执行此操作,例如spt_values

select dateadd(day, v.number - 1, startdate) as thedate, count(*) 
from tb_leave l join 
    spt_values v 
    on dateadd(day, v.number - 1, startdate) <= l.enddate 
group by dateadd(day, v.number - 1, startdate) 
order by 1; 
+0

在第一个查询我有这个 声明终止。报表完成前,最大递归100已用尽。 – user2530833 2014-09-23 02:09:49