2012-04-04 33 views
1

我想創建一個條形圖,顯示月度基礎上可用的對象數量。所有行都有開始和結束日期。我知道該怎麼做了數單月:使用TSQL開始和結束日期對象的每月計數

SELECT COUNT(*) As NumberOfItems 
FROM Items 
WHERE DATEPART(MONTH, Items.StartDate) <= @monthNumber 
AND DATEPART(MONTH, Items.EndDate) >= @monthNumber 

現在我想確實創建SQL得到月份數,並使用一個單一的SELECT語句中的項目數量。

有沒有完成此任務的優雅方式?我知道我必須考慮年份數字。

+0

因此,爲了澄清「我知道我必須考慮年份編號」,無論物品的日期範圍是什麼,或者您希望(例如)2011年3月和2012年3月爲不同行? – AakashM 2012-04-04 08:36:42

回答

3

假設Sql Server 2005或更新版本。

CTE部分將返回@startDate和@endDate之間跨月的數字。主體在Items.StartDate和Items.EndDate上加入了與項目執行相同轉換的月份數字。

; with months (month) as (
    select datediff (m, 0, @startDate) 
    union all 
    select month + 1 
    from months 
    where month < datediff (m, 0, @endDate) 
) 
select year (Items.StartDate) Year, 
     month (Items.StartDate) Month, 
     count (*) NumberOfItems 
    from months 
    inner join Items 
    on datediff (m, 0, Items.StartDate) <= months.month 
    and datediff (m, 0, Items.EndDate) >= months.month 
    group by 
     year (Items.StartDate), 
     month (Items.StartDate) 

注意:如果你打算跨越百元以上的幾個月裏,你將需要option (maxrecursion 0)在查詢結束。

相關問題