根据日期范围汇总每月的天数

时间:2011-03-06 20:42:06

标签: sql tsql

作为一名C#开发人员,在尝试创建基于T-SQL的纯解决方案时遇到一系列日期范围的日常/月份问题时,我正在摸不着头脑。

我有一组数据看起来像这样:

UserID  Department  StartDate   EndDate
======  ==========  ==========  ==========
1       A           2011-01-02  2011-01-05
1       A           2011-01-20  2011-01-25
1       A           2011-02-25  2011-03-05
1       B           2011-01-21  2011-01-22
2       A           2011-01-01  2011-01-20
3       C           2011-01-01  2011-02-03

日期范围不重叠,可能跨越几个月,特定用户和部门可能在一个月内存在多个范围。 我想要做的是总结每个用户,部门,年和月的天数(包括),像这样(在我的例子中保留任何数学错误......):

UserID  Department  Year  Month  Days
======  ==========  ====  =====  ====
1       A           2011  01     10
1       A           2011  02     4
1       A           2011  03     5
1       B           2011  01     2
2       A           2011  01     20
3       C           2011  01     31
3       C           2011  02     3

此数据将进入报告工具使用的新表格。 我希望问题描述足够清楚,这是我在这里的第一篇帖子,温柔: - )

提前致谢!

1 个答案:

答案 0 :(得分:8)

工作样本

-- sample data in a temp table
declare @t table (UserID int, Department char(1), StartDate datetime, EndDate datetime)
insert @t select
1 ,'A', '2011-01-02','2011-01-05'union all select
1 ,'A', '2011-01-20','2011-01-25'union all select
1 ,'A', '2011-02-25','2011-03-05'union all select
1 ,'B', '2011-01-21','2011-01-22'union all select
2 ,'A', '2011-01-01','2011-01-20'union all select
3 ,'C', '2011-01-01','2011-02-03'

-- the query you need is below this line    

select UserID, Department,
    YEAR(StartDate+v.number) Year,
    MONTH(StartDate+v.number) Month, COUNT(*) Days
from @t t
inner join master..spt_values v
  on v.type='P' and v.number <= DATEDIFF(d, startdate, enddate)
group by UserID, Department, YEAR(StartDate+v.number), MONTH(StartDate+v.number)
order by UserID, Department, Year, Month