我發現了一個足夠好的解決方法。我一直在尋找如何解決這個問題,並發現我可以使用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'的代碼中。但我想這是另一個問題的故事。
看到你如何做滾動計數將有助於查看條件的範圍和數據如何分區。此外,這個問題似乎是關於查詢,而不是關於在報表生成器3.0中構建報表。 – Raybarg
有關構建報告的信息是爲了提供更多我需要的內容。然而,是的 - 這是正確的,它更關於查詢。對不起,如果它很混亂。我想在經過幾次嘗試之後,我向目標邁進了一步,我找到了一種方法來計算它,並有可能在不改變每個月的值的情況下更改一系列日期。簡而言之,簡而言之:在臨時表內部選擇總和(o.number_of_activities-c.number_of_activities)over(ORDER BY c.full_year,c.month_number)作爲[backlog]'。現在我需要找到如何將其添加到代碼的其餘部分。不管怎樣,謝謝! – Janek
是的,您的ORDER BY在計算聚合滾動數時非常重要,正如您所描述的那樣。沒有查詢就無法指出問題。更多關於OVER(); https://msdn.microsoft.com/en-us/library/ms189461.aspx – Raybarg