SELECT CASE t-sql中的计算列

时间:2014-04-27 22:37:20

标签: sql sql-server-2008 tsql

我有一个计算列:

BilledAmount = 
    CASE 
        WHEN CoverageItem  in ('MED','RNB', 'LAB')  
            THEN  ISNULL(SUM(ISNULL(hb.BilledAmt,0)),0)
        END
    FROM HospitalBill hb with(nolock) 

基本上,它所做的是总结从医院百姓表中使用例如MED的覆盖项目计费的金额...我不想做的是添加另一个案例,如果CoverageItem ='BEN'。 ..那么BilledAmount将是BilledAmounts与'LAB'和'BEN'的CoverageItem的总和..是可能的..

2 个答案:

答案 0 :(得分:1)

SELECT
  ProviderCode, 
  CASE
    WHEN CoverageItem IN ('LAB', 'BEN') THEN 'LAB'
    ELSE CoverageItem
  END AS CoverageItem,
  SUM(hb.BilledAmt) AS BilledAmount
FROM HospitalBill hb
Group BY 
  ProviderCode, 
  CASE
    WHEN CoverageItem IN ('LAB', 'BEN') THEN 'LAB'
    ELSE CoverageItem
  END

答案 1 :(得分:0)

我认为Sum应该在你的案例陈述之外。即。

SUM(
CASE 
    WHEN CoverageItem  in ('MED','RNB', 'LAB')  
        THEN  ISNULL(hb.BilledAmt,0)
    ELSE
        0
    END
FROM HospitalBill hb with(nolock)) as BilledAmount