上CTE

2015-04-30 47 views
0
遞歸計算

我正在尋找一種方式,如何計算公式如下:上CTE

month 1 
result_1 = result_0 + (number_of_open - number_of_close), where result_0 = 0 
month 2 
result_2 = result_1 + (number_of_open - number_of_close) 
month 3 
result_3 = result_2 + (number_of_open - number_of_close) 

我知道如何計算它時,結果從一開始就顯示,意思是:

enter image description here

但是當我有選擇的,例如從2015年2月1日,一些日期,它不能正確計算:

enter image description here

它似乎從所採取的時刻算起。 有什麼想法如何解決它?

+0

看到你如何做滾動計數將有助於查看條件的範圍和數據如何分區。此外,這個問題似乎是關於查詢,而不是關於在報表生成器3.0中構建報表。 – Raybarg

+0

有關構建報告的信息是爲了提供更多我需要的內容。然而,是的 - 這是正確的,它更關於查詢。對不起,如果它很混亂。我想在經過幾次嘗試之後,我向目標邁進了一步,我找到了一種方法來計算它,並有可能在不改變每個月的值的情況下更改一系列日期。簡而言之,簡而言之:在臨時表內部選擇總和(o.number_of_activities-c.number_of_activities)over(ORDER BY c.full_year,c.month_number)作爲[backlog]'。現在我需要找到如何將其添加到代碼的其餘部分。不管怎樣,謝謝! – Janek

+0

是的,您的ORDER BY在計算聚合滾動數時非常重要,正如您所描述的那樣。沒有查詢就無法指出問題。更多關於OVER(); https://msdn.microsoft.com/en-us/library/ms189461.aspx – Raybarg

回答

0

我發現了一個足夠好的解決方法。我一直在尋找如何解決這個問題,並發現我可以使用SUM() OVER(),它將作爲Running Total運行。但是如果我需要它在給定的時間範圍內工作,我不得不使用子查詢,所以我無法使用CTE並且必須使用臨時表。我的代碼是:

IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL BEGIN 
    drop table #Temp1 
end 

SELECT * into #Temp1 
    from (
SELECT 
datepart(yy, t3.[datestamp]) AS full_year 
,datepart(mm, t3.[datestamp]) AS month_number 
,count(*) as number_of_activities 
,t2.affected_item 
FROM [sm70prod].[dbo].[ACTSVCMGTM1] AS t3 
JOIN [sm70prod].[dbo].[INCIDENTSM1] AS t2 ON t3.number = t2.incident_id 
WHERE 
t2.affected_item like 'Service_name' 
AND (t3.[type] LIKE 'Open') 
GROUP BY t2.affected_item, datepart(yy, t3.[datestamp]), datepart(mm, t3.[datestamp]) 
) 
as databases (full_year, month_number, number_of_activities, affected_item) 

; 
IF OBJECT_ID('tempdb..#Temp2') IS NOT NULL BEGIN 
     drop table #Temp2 
end 

SELECT * into #Temp2 
    from (
SELECT 
datepart(yy, t3.[datestamp]) AS full_year 
,datepart(mm, t3.[datestamp]) AS month_number 
,count(*) as number_of_activities 
,t2.affected_item 
FROM [sm70prod].[dbo].[ACTSVCMGTM1] AS t3 
JOIN [sm70prod].[dbo].[INCIDENTSM1] AS t2 ON t3.number = t2.incident_id 
WHERE 
t2.affected_item like 'Service_name' 
AND (t3.[type] LIKE 'Closed') 
GROUP BY t2.affected_item, datepart(yy, t3.[datestamp]), datepart(mm, t3.[datestamp]) 
) 
as databases (full_year, month_number, number_of_activities, affected_item) 


select * from (select sum(o.number_of_activities - c.number_of_activities) over (ORDER BY c.full_year, c.month_number) as [backlog] 
from #Temp1 o full join #Temp2 c on o.full_year = c.full_year and o.month_number = c.month_number) sub 
--where 'time condition' 

我可以把我的日期/時間條件放在'where'子句中。

現在的問題是如何正確地將它添加到我使用CTE和少數'選擇'結合'union all'的代碼中。但我想這是另一個問題的故事。