计算日期范围内的总交易数

时间:2014-09-23 02:01:35

标签: sql sql-server

我有这些数据: 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

我想在特定的日子里返回所有的假期。 out put:

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

1 个答案:

答案 0 :(得分: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;