我正在寻找一种方法,如何计算公式如下:
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)
我知道如何从最开始显示结果时计算它,意味着:
但是当我选择了一些日期时,例如从2015年2月1日开始,它没有正确计算:
似乎从拍摄时刻算起。 有什么想法可以解决吗?
答案 0 :(得分:0)
我找到了一个足够好的解决方法。我一直在寻找如何解决这个问题,并发现我可以使用SUM() OVER(),它将作为一个运行总计。但是如果我需要它在给定的时间范围内工作,我必须使用子查询,所以我无法使用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'相结合。但我想这是另一个问题的故事。