2011-03-06 60 views
5

作爲一名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 

這些數據將進入報表工具使用的新表格。 我希望問題描述足夠清楚,這是我第一次在這裏發帖,要溫​​柔:-)

在此先感謝!

回答

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 
+0

謝謝!工作正常,有趣的使用** master..spt_values **,沒有遇到過那個系統表。有關** master..spt_values **的更多信息,請參見[此處](http://stackoverflow.com/questions/4273723/what-is-the-purpose-of-system-table-table-master-spt-價值觀和什麼 - 是最MEA)。 – 2011-03-06 21:44:17

+0

+1使用原始「理貨表」。 ;-) – 2011-03-07 02:57:44