2017-07-11 66 views
2

我需要從條件'B'之後的字段總和中減去字段的總和如何從SQL Server 2014中的另一個總和值中減去Sum值?

我試過了不同的代碼組合來嘗試獲取我正在查找的內容對於。但我認爲最簡單的,愚蠢的代碼是這一個:

SELECT A.AccountNumber 
     ,SUM(
     (SELECT SUM(FinTransAmt) 
      FROM FinTransMaster 
      WHERE FinTransCode IN ('Code01', 'Code02', 'Code03', 'Code04') 
     ) 
    -  -- Minus sign 
     (SELECT SUM(FinTransAmt) 
      FROM FinTransMaster 
     WHERE FinTransCode IN ('Code05', 'Code06', 'Code07', 'Code08') 
     ) 
    ) AS Interest 

FROM FinTransMaster ft 
    , Account a 

WHERE ft.AcctID=a.AccountId 
    AND a.AccountNumber = '101010101' 
    AND CAST (ft.Created as date) >= '2017-06-01' 
    AND CAST (ft.Created as date) <= '2017-07-01' 

GROUP BY A.AccountNumber 

回答

1

也許是另一種選擇

SELECT A.AccountNumber 
     ,Interest = IsNull(SUM(case when FinTransCode IN ('Code01', 'Code02', 'Code03', 'Code04') then FinTransAmt end),0) 
       - IsNull(SUM(case when FinTransCode IN ('Code05', 'Code06', 'Code07', 'Code08') then FinTransAmt end),0) 
FROM FinTransMaster ft 
    , Account a 
WHERE ft.AcctID=a.AccountId 
    AND a.AccountNumber = '101010101' 
    AND CAST (ft.Created as date) >= '2017-06-01' 
    AND CAST (ft.Created as date) <= '2017-07-01' 
GROUP BY A.AccountNumber 
+0

謝謝你,約翰。這看起來很整齊。只是一個簡單的問題,將NULL值更改爲0的代碼是什麼? _____ CASN當ISNULL(FinTransCode,0)IN('Code01','Code02'.....)然後... – user1777929

+0

@ user1777929對不起,多任務處理。我打算把IsNull()忘了。查看更新的答案 –

1

我想你可以通過使用條件彙總如下使用查詢:

SELECT A.AccountNumber 
    ,Sum(case when FinTransCode in ('Code05', 'Code06', 'Code07', 'Code08') then -FinTransAmt else FinTransAmt end) as Interest 
FROM FinTransMaster ft 
    Join Account a 
    On ft.AcctID=a.AccountId 
    AND a.AccountNumber = '101010101' 
    AND CAST (ft.Created as date) >= '2017-06-01' 
    AND CAST (ft.Created as date) <= '2017-07-01' 
GROUP BY A.AccountNumber 
+0

好使用邏輯開關,但可能有需要排除的代碼。 –

+0

謝謝你的回答,坎南。我非常感激。 – user1777929

相關問題