gpt4 book ai didi

SQL 多 CASE 语句返回 0 而不是 NULL

转载 作者:行者123 更新时间:2023-12-02 06:23:26 26 4
gpt4 key购买 nike

我有以下 SQL Case 语句,只要年份匹配 MF.Date & M.MemberCurrentYear,它就可以完美运行。会出现年份不匹配的情况,这会返回 NULL 的余额。我希望它返回零。

SELECT SUM(CASE WHEN Type = 1 THEN Amount ELSE Amount * - 1 END) AS Balance
FROM dbo.MemberFinancials AS MF
INNER JOIN dbo.Members AS M ON MF.MemberID = M.MemberID
AND DATEPART(yyyy, MF.Date) = M.MemberCurrentYear
INNER JOIN dbo.FinancialTypes AS FT ON MF.FinancialTypeID = FT.FinancialTypeID

谢谢

最佳答案

SELECT     

ISNULL(SUM(CASE WHEN Type = 1 THEN Amount ELSE Amount * - 1 END),0) AS Balance
FROM dbo.MemberFinancials AS MF INNER JOIN
dbo.Members AS M ON MF.MemberID = M.MemberID AND DATEPART(yyyy, MF.Date) = M.MemberCurrentYear INNER JOIN
dbo.FinancialTypes AS FT ON MF.FinancialTypeID = FT.FinancialTypeID

使用 ISNULL(如果您愿意,也可以使用 COALESCE...)

关于SQL 多 CASE 语句返回 0 而不是 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5223360/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com