2017-02-14 134 views
0

我需要运行以下查询,我知道下面的是不正确的,但也许这会给你我想要输出的东西的想法。sum函数与where子句 - SQL Server

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 <> ''(不为空)

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

输出 - PayMonth = ''(空白)

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

后一些样品的数据和输出你想要什么 – mohan111

回答

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] 
+0

我收到以下错误:附近有语法错误)“ - 对不起,不知道如何正确的语法在查询上。 –

+0

更改了代码,请立即查看@ChantelleBrink –

+0

完美,非常感谢你.... –