缺少值时,在SQL中运行Total作为SUM()OVER()

时间:2015-05-04 11:38:11

标签: sql-server-2012 running-total

我正在尝试计算“运行总计”并且它的工作正常,但只有在我正在调整的值可用时才能正常运行。当一些不可用时,计算出错,一些NULL发生,最后运行总计不正确,这是这种情况的例子:

this is when there was no values for some month_number

我希望在下面的屏幕截图中设置(添加缺少的月份),这应该在最后给出正确的运行总计(在这里命名为backlog):

expected result

有没有办法将full_year和month_number列定义为可见,当没有值时设置为'0'值?

我目前的查询如下:

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

SELECT * into #Temp4
   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'
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..#Temp5') IS NOT NULL BEGIN
       drop table #Temp5
end

SELECT * into #Temp5
   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'
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 o.full_year 
,o.month_number
,o.number_of_activities as [open]
,c.number_of_activities as [close]
,sum(o.number_of_activities - c.number_of_activities) over (ORDER BY c.full_year, c.month_number) as [backlog]
from #Temp4 o full join #Temp5 c on o.full_year = c.full_year and o.month_number = c.month_number) as sub
order by full_year, month_number

2 个答案:

答案 0 :(得分:0)

https://msdn.microsoft.com/en-gb/library/ms190349%28v=sql.110%29.aspx
尝试使用合并功能:

COALESCE(someattribute, 0);

如果属性为NULL,则将使用值零。

另请注意:

比较没有正则表达式的varchars时,你应该使用=运算符而不是LIKE运算符。

答案 1 :(得分:0)

我找到了答案。对于缺少的月份,我可以使用以下代码:

    If(OBJECT_ID('tempdb..#Temp6') Is Not Null)
Begin
    Drop Table #Temp6
End

create table #Temp6

(
full_year int
,month_number int
)
; WITH cteStartDate AS
 (SELECT StartDate = '2007-01-01'),
 cteSequence(SeqNo) 
     AS (SELECT 0 
         UNION ALL 
         SELECT SeqNo + 1 
         FROM   cteSequence 
         WHERE  SeqNo < DATEDIFF(MM,(SELECT StartDate FROM cteStartDate),getdate())) 

INSERT INTO #Temp6
SELECT datepart(yy, DATEADD(MM,SeqNo,(SELECT StartDate FROM cteStartDate))) AS full_year 
,datepart(mm, DATEADD(MM,SeqNo,(SELECT StartDate FROM cteStartDate))) AS month_number
FROM   cteSequence
OPTION (MAXRECURSION 0) 

然后我可以将full join#Temp4一起使用,添加ISNULL(o.number_of_activities, 0),同样适用于#Temp5,这样就可以了。