I need to subtract a sum of a field which follows condition 'A' from the sum of a field which follows condition 'B'
I've tried different combinations of code to try and get what I'm looking for. But I think the simplest, stupidest code is this one:
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
Perhaps another option
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