SELECT f.CaseId
, SUM(CASE WHEN f.FeeType = 29 THEN f.UnitCost END) AS AdminFee
, SUM(CASE WHEN f.FeeType = 1 THEN f.UnitCost END) AS SubFee
, SUM(CASE WHEN f.FeeType = 15 THEN f.UnitCost END) AS ContFee
FROM dbo.Fee f
GROUP BY f.CaseId
对于上述查询,我试图在同一个select语句中添加FeeType = 29和FeeType = 1的UnitCost并将其存储在TotalCost中。
答案 0 :(得分:2)
要么添加新行
sum (case when f.FeeType IN (1, 29) then f.UnitCost END) as TotalCost
或者您将查询用作子查询并添加
select
CaseId,
AdminFee,
SubFee,
ContFee,
AdminFee + SubFee as TotalCost
from (
SELECT f.CaseId
, SUM(CASE WHEN f.FeeType = 29 THEN f.UnitCost END) AS AdminFee
, SUM(CASE WHEN f.FeeType = 1 THEN f.UnitCost END) AS SubFee
, SUM(CASE WHEN f.FeeType = 15 THEN f.UnitCost END) AS ContFee
FROM dbo.Fee f
GROUP BY f.CaseId) s