总计选择和条件和分组

时间:2014-09-23 14:30:33

标签: sql

------------------------------------------
Id       | CaseId   | FeeType |     Cost |
-----------------------------------------
1017796  | 2697789  |      29 |       50  
1018167  | 2697789  |       1 |      150 
1019493  | 2697789  |      15 |       30
1017799  | 2697790  |      29 |       50 
1018168  | 2697790  |       1 |      150 
1019494  | 2697790  |      15 |       0
-----------------------------------------

我希望输出为 如果承包商费用等于0,则TotalFee应为0而不是总数 AdminFee + SubFee + ContFee

------------------------------------------------------------------
CaseId   | AdminFee  | SubFee  | ContFee | TotalAdmin | TotalFee
------------------------------------------------------------------
2697789  |       50  |    150  |     30  |     200    |  230
------------------------------------------------------------------
2697790  |       50  |    150  |     0   |     200    |    0
------------------------------------------------------------------

@" select distinct a.CaseID 
  , sum(CASE WHEN b.FeeType = 29 THEN b.Cost END) AS AdminFee
  , sum(CASE WHEN b.FeeType = 1 THEN b.Cost END) AS SubFee
  , sum(CASE WHEN b.FeeType = 15 THEN b.Cost END) AS ContFee
  ,sum (case when b.FeeType IN (1, 29) then b.Cost END) as TotalAdmin

From Fee a
GROUP BY a.CaseId

如果没有承包商费用,如何修改上述选择语句以使总计为0 如果有承包商,那么TotalFee = AdminFee + SubFee + ContFee

1 个答案:

答案 0 :(得分:0)

如果我理解得很好,你可以使用ISNULL或COALESCE声明:

ISNULL(字段,值,如果为null) -

 ISNULL(sum(CASE WHEN b.FeeType = 15 THEN b.Cost END) AS ContFee)

或使用CASE AND ISNULL:

 CASE
   IF b.FeeType != null THEN b.Cost
   ELSE 0
 END AS ContFee