在CASE SQL SERVER中避免NULL值

时间:2019-07-19 09:15:15

标签: sql sql-server select case

如何通过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

2 个答案:

答案 0 :(得分:1)

总和内的用例

 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

答案 1 :(得分:1)

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子句将完全不需要CASELEFT JOIN保留所有玩家,即使那些没有该产品类型的玩家也是如此。