Sql 计算日期范围内的交易记录总数
我有以下数据: 离开 我想在一个特定的日子内归还所有的假期。 输出:Sql 计算日期范围内的交易记录总数,sql,sql-server,Sql,Sql Server,我有以下数据: 离开 我想在一个特定的日子内归还所有的假期。 输出: 您可以使用递归CTE展开日期,然后使用分组依据: with cte as ( select startdate as thedate, enddate from tb_leave union all select dateadd(day, 1, startdate), enddate from cte where startdate < enddat
您可以使用递归CTE展开日期,然后使用
分组依据
:
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);
它必须是单个查询吗?在第一个查询中,我将终止该语句。在语句完成之前,已耗尽最大递归100。
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
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);
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;