2014-10-29 94 views
0

我在SSRS中創建報告,應該顯示一個月內的事件持續時間。這份報告應該在每個日曆月分別進行12次。目前我的選擇有12個硬編碼選擇,每個月都有。我怎樣才能做到這一點,重複12次選擇,只是迭代開始和結束時間,無論是在SQL語言(適用於視圖),或從SSRS更好?謝謝。最後一行SSRS循環選擇月份

SELECT DATEDIFF(mi, '2014-01-01 00:00:00.000', end_date) AS total_event 
    FROM MY_TABLE 
    WHERE (start_date <= '2014-01-01 00:00:00.000') AND (end_date BETWEEN '2014-01-01 00:00:00.000' AND '2014-02-01 00:00:00.000') 

    UNION ALL 

    SELECT DATEDIFF(mi, start_date, '2014-02-01 00:00:00.000') AS total_event 
    FROM MY_TABLE 
    WHERE (end_date >= '2014-02-01 00:00:00.000') AND (start_date BETWEEN '2014-01-01 00:00:00.000' AND '2014-02-01 00:00:00.000') 

    UNION ALL 

    SELECT DATEDIFF(mi, '2014-01-01 00:00:00.000', '2014-02-01 00:00:00.000') AS total_event 
    FROM MY_TABLE 
    WHERE (start_date <= '2014-01-01 00:00:00.000') AND (end_date >= '2014-02-01 00:00:00.000') 

    UNION ALL 

    SELECT DATEDIFF(mi, start_date, end_date) AS total_event 
    FROM MY_TABLE 
    WHERE (start_date BETWEEN '2014-01-01 00:00:00.000' AND '2014-02-01 00:00:00.000') AND (end_date BETWEEN '2014-01-01 00:00:00.000' AND '2014-02-01 00:00:00.000') 

回答

0

嘗試使用下面的腳本

declare @start datetime 
declare @end datetime 

set @start = '2014-01-01' --firstDay year 
set @end = '2014-12-31' --last Day of year 

;with cte as 
(
select @start firstday, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATEADD(month, DATEDIFF(month, 0, @start), 0))+1,0)) lastday, 1 MM 
union all 
select DATEADD(month, DATEDIFF(month, 0, lastday + 1), 0) , DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATEADD(month, DATEDIFF(month, 0, lastday + 1), 0))+1,0)), MM + 1 
from cte 
where lastday < @end 
) 
SELECT * FROM CTE C 
--LEFT OUTER JOIN MY_TABLE M ON (M.start_date <= firstday) AND (end_date BETWEEN firstday AND lastday) 

,只需取消註釋

--LEFT OUTER JOIN MY_TABLE M ON (M.start_date <= firstday) AND (end_date BETWEEN firstday AND lastday) 
0

你可以試試這個:

SELECT 
    DATEADD(MONTH, DATEDIFF(MONTH, 0, start_date), 0) AS [month], DATEDIFF(MINUTE, DATEADD(MONTH, DATEDIFF(MONTH, 0, start_date), 0), end_date) AS total_event 
FROM 
    MY_TABLE 
WHERE 
    YEAR(start_date) = 2014 
ORDER BY 
    [month];