我需要从条件“B”之后的字段之和中减去条件“A”之后的字段之和。
我尝试过不同的代码组合来尝试获取我正在寻找的东西。但我认为最简单,最愚蠢的代码是这样的:
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
也许另一种选择
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
我认为你可以使用条件聚合来使用你的查询:
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