【问题标题】:Avoid NULL value in CASE SQL SERVER避免在 CASE SQL SERVER 中使用 NULL 值
【发布时间】:2019-07-19 09:15:15
【问题描述】:

如何通过 P.Id 避免 CASE 和 SUM 中的 NULL 值。问题是我在 DPB 表中有多个 DPB.ProductTypeId

SELECT  P.[Id], 
        CASE 
        WHEN DPB.ProductTypeId = 1 THEN SUM(DPB.BonusAmount)
        END AS [CasinoBonus]
FROM Player P           
JOIN PlayerBonus DPB ON P.[Id] = DPB.[PlayerId]
group by P.[Id],DPB.ProductTypeId

【问题讨论】:

  • 添加一些示例数据和您的预期输出。并添加您面临的问题。
  • sum 已经忽略空值。
  • 如果我输入总和,我得到两行,一行是汇总值,另一行是 NULL

标签: sql sql-server select case


【解决方案1】:

在 sum 中的用例

 SELECT  P.[Id], 
            sum(CASE 
            WHEN DPB.ProductTypeId = 1 THEN DPB.BonusAmount
            else 0
            END) AS [CasinoBonus]
    FROM Player P           
    JOIN PlayerBonus DPB ON P.[Id] = DPB.[PlayerId]
    where P.[Id] is not null and DPB.[PlayerId] is not null
    group by P.[Id],DPB.ProductTypeId

【讨论】:

  • 您的CASE 表达式可能需要ELSE 0 大小写。
【解决方案2】:

case 应该是sum() 的参数。您的查询应如下所示:

SELECT P.[Id], 
       SUM(CASE WHEN DPB.ProductTypeId = 1 THEN DPB.BonusAmount
           END) AS [CasinoBonus]
FROM Player P JOIN
     PlayerBonus DPB
     ON P.[Id] = DPB.[PlayerId]
GROUP BY P.[Id];

请注意,您不希望 DPB.ProductTypeId 出现在 GROUP BY 中。

也就是说,您可能只是想要:

SELECT P.[Id], 
       SUM(DPB.BonusAmount) AS [CasinoBonus]
FROM Player P LEFT JOIN
     PlayerBonus DPB
     ON P.[Id] = DPB.[PlayerId] AND 
        DPB.ProductTypeId = 1
GROUP BY P.[Id];

将条件移至WHERE 子句完全消除了对CASE 的需求。 LEFT JOIN 保留所有玩家,即使是那些没有该产品类型的玩家。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 2014-03-13
    • 1970-01-01
    • 2017-09-12
    相关资源
    最近更新 更多