SQL Server Case 语句和聚合函数

标签 sql sql-server sum case-statement

我有以下表格数据:

SELECT [Quote ID], [Deductible Plan], [Age ID], [Number of Members] 
FROM finalResult_001

1381    $750 Deductible Plan    Age 65      10
1381    $750 Deductible Plan    Age 85+     10
1371    $150 Deductible Plan    Age 65      10
1371    $150 Deductible Plan    Age 85+     10

我正在寻找以下结果:

Quote ID Deductible Plan       Age 65      Age 85+
1381    $750 Deductible Plan    10          10
1371    $150 Deductible Plan    10          10

我想按报价 ID 和免赔额计划进行分组,并应按年龄 ID 列求和,但我不知道该怎么做,这是我的尝试:

SELECT [Quote ID], [Deductible Plan],

case when [Age ID] = 'Age 65' THEN SUM([Number of Members]) else 0 END AS [Age 65],   
case when [Age ID] = 'Age 85+' THEN SUM([Number of Members]) else 0 END AS [Age 85+]

FROM finalResult_001
GROUP BY [Quote ID], [Age ID], [Deductible Plan]

结果:

Quote ID Deductible Plan        Age 65      Age 85+
1381    $750 Deductible Plan    0           10
1381    $750 Deductible Plan    10          0
1371    $150 Deductible Plan    0           10
1371    $150 Deductible Plan    10          0

我如何对年龄 ID 进行求和来得到结果:

Quote ID Deductible Plan        Age 65      Age 85+
1381    $750 Deductible Plan    10          10
1371    $150 Deductible Plan    10          10

最佳答案

将 CASE 应用于 [Number of Members] 而不是 SUM([Number of Members]),并且不按 [Age ID]:

SELECT
  [Quote ID],
  [Deductible Plan],
  SUM(case when [Age ID] = 'Age 65'  THEN [Number of Members] else 0 END) AS [Age 65],   
  SUM(case when [Age ID] = 'Age 85+' THEN [Number of Members] else 0 END) AS [Age 85+]
FROM dbo.finalResult_001
GROUP BY [Quote ID], [Deductible Plan]
;

关于SQL Server Case 语句和聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25112213/

相关文章:

sql - Azure 数据库-SQL N :N Query

MYSQL、Max、Group by 和 Max

SQL Server 自动去除尾随空格

php - Propel:无交叉表的多对多关系

sql - 选择列表中的列无效,因为它既不包含在聚合函数中,也不包含在 SQL Server 的 GROUP BY 子句中

SQL 服务器 : find break in dates to show unique rows

linq - 如果求和值全部为空,如何使 linq Sum 返回空

mysql - SQL Server 和 MySQL 之间的 SUM() 函数差异

mysql - 使用 MySQL 创建的 View 中的 Sum 列

sql - 传入一组值以通过一个原始查询更新多行