带有where子句的Sum函数 - SQL Server

时间:2017-02-14 05:22:25

标签: sql-server sum where

我需要运行以下查询,我知道下面的内容不正确但也许这会让你知道我需要输出的内容。

SELECT 
    [SchemeCd],          
    SUM([PayAmt] WHERE [ServiceMonth] = '201602'and [PayMonth] <> '') as [Feb-2016_P],
    SUM([PayAmt] WHERE [ServiceMonth] = '201603'and [PayMonth] <> '') as [Mar-2016_P]
INTO 
    [Claim Totals]
FROM 
    [All Claims]
GROUP BY 
    [SchemeCd]

因此,我需要计算每个特定服务月份的支付金额总和,其中支付月份不为空白。然后我会再做一笔金额来计算每个特定服务月的支付金额总和,其中支付月份为空白。

原始表

[PayAmt]|  [ServiceMonth]|  [PayMonth 

 500          201602         201602
 900          201602
 500          201602         201602 
 500          201603         201603
 600          201603       
 600          201603         201603 

输出 - PayMonth&lt;&gt; ''(不是空白)

[PayAmt]|  [ServiceMonth]|  [PayMonth  
 1000       201602           201602
 1100       201603           201603

输出 - PayMonth =''(空白)

[PayAmt]|  [ServiceMonth]|  [PayMonth  
 900        201602           201602
 600        201603           201603

1 个答案:

答案 0 :(得分:1)

根据我的理解,这应该是你的代码

SELECT [SchemeCd],SUM(Case WHEN [ServiceMonth] = '201602'and [PayMonth] <> '' THEN [PayAmt] END) as [Feb-2016_P],
SUM(Case WHEN [ServiceMonth] = '201603'and [PayMonth] <> '' THEN [PayAmt] END) as [Mar-2016_P]

INTO [Claim Totals]
FROM [All Claims]
GROUP BY [SchemeCd]