带有 where 子句的 Sum 函数 - SQL 服务器
Sum Function with a where clause - 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]
因此,我需要计算每个特定服务月份的支付金额总额,其中支付月份不为空。然后我会做另一笔计算每个特定服务月的支付金额总和,其中支付月为空。
原版Table
[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
据我了解,这应该是您的代码
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]
我需要 运行 以下查询,我知道以下不正确,但也许这会让您了解我需要输出什么。
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]
因此,我需要计算每个特定服务月份的支付金额总额,其中支付月份不为空。然后我会做另一笔计算每个特定服务月的支付金额总和,其中支付月为空。
原版Table
[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
据我了解,这应该是您的代码
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]