2011-03-07 100 views
2

我有以下SQL Case語句,只要年數匹配MF.Date & M.MemberCurrentYear即可完美工作。將會出現這樣的情況,即年份不匹配,並返回餘額NULL。我希望它返回一個零。SQL多個CASE語句返回0而不是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 

感謝

回答

5
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 ...)

2
SELECT 
    COALESCE(
     SUM(CASE WHEN Type = 1 THEN Amount ELSE Amount * - 1 END) 
    , 0) AS Balance 
3
SELECT ISNULL(SUM(CASE WHEN Type = 1 THEN Amount ELSE Amount * - 1 END), 0) AS Balance