我试图在SQL Select语句中添加2个值

时间:2014-09-15 14:05:22

标签: sql

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中。

1 个答案:

答案 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