[英]Avoid NULL value in CASE SQL SERVER
How to avoid NULL values in CASE and SUM by P.Id. 如何通过P.Id避免CASE和SUM中的NULL值。 Problem is that i have more than one DPB.ProductTypeId in DPB table
问题是我在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
use case when inside 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
The case
should be the argument to the sum()
. case
应该是sum()
的参数。 You query should look like this: 您的查询应如下所示:
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];
Note that you don't want DPB.ProductTypeId
in the GROUP BY
. 请注意,您不需要
GROUP BY
DPB.ProductTypeId
。
That said, you may simply want: 也就是说,您可能只想:
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];
Moving the condition to the WHERE
clause removes the need for the CASE
entirely. 将条件移至
WHERE
子句完全不需要CASE
。 The LEFT JOIN
keeps all players, even those that don't have that product type. LEFT JOIN
保留所有玩家,即使那些没有该产品类型的玩家也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.