我需要减去一个字段的总和,该字段遵循条件' A'来自条件' B'
之后的字段的总和我尝试了不同的代码组合来尝试获取我正在寻找的内容。但我认为最简单,最愚蠢的代码就是这个:
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
答案 0 :(得分: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
答案 1 :(得分: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