如何在case语句中使用SUM

时间:2013-07-29 15:04:20

标签: sql sql-server tsql

如何从列列表中选择第一个非零值的总和 - 不包括组中的列。这是我写的查询,但我必须在组中包含所有这些列(我不想这样做)

Select CpnyID,H.Acct,A.Descr, 
case when H.YtdBal12 > 0 then sum(H.YtdBal12)
     when H.YtdBal11 > 0 then sum(H.YtdBal06)
     when H.YtdBal10 > 0 then sum(H.YtdBal10)
     when H.YtdBal09 > 0 then sum(H.YtdBal09)
     when H.YtdBal08 > 0 then sum(H.YtdBal08)
     when H.YtdBal07 > 0 then sum(H.YtdBal07)
     when H.YtdBal06 > 0 then sum(H.YtdBal06)
     when H.YtdBal05 > 0 then sum(H.YtdBal05)
     when H.YtdBal04> 0 then sum(H.YtdBal04)
     when H.YtdBal03 > 0 then sum(H.YtdBal03)
     when H.YtdBal02  > 0 then sum(H.YtdBal02)
     when H.YtdBal01 > 0 then sum(H.YtdBal01)
     when H.YtdBal00 > 0 then sum(H.YtdBal00)
END
from AcctHist H,Account A,PSSFAAssetClass C
where A.Acct = H.Acct
and (H.Acct = C.Acct or H.Acct  = C.AccDeprAcct) 
and FiscYr = 2013
group by CpnyID,H.Acct,A.Descr
order by CpnyID,H.Acct

2 个答案:

答案 0 :(得分:2)

试试这个:

SUM(COALESCE(H.YtdBal12, H.YtdBal11, H.YtdBal10...)

如果值实际为0而不是null,则每列可能需要NULLIF()。 像:

SUM(COALESCE(NULLIF(H.YtdBal12,0),NULLIF(H.YtdBal11,0), etc...)

答案 1 :(得分:2)

您希望将sum()移到案例之外:

Select CpnyID, H.Acct, A.Descr, 
Sum(case when H.YtdBal12 > 0 then H.YtdBal12
     when H.YtdBal11 > 0 then H.YtdBal06
     when H.YtdBal10 > 0 then H.YtdBal10
     when H.YtdBal09 > 0 then H.YtdBal09
     when H.YtdBal08 > 0 then H.YtdBal08
     when H.YtdBal07 > 0 then H.YtdBal07
     when H.YtdBal06 > 0 then H.YtdBal06
     when H.YtdBal05 > 0 then H.YtdBal05
     when H.YtdBal04> 0 then H.YtdBal04
     when H.YtdBal03 > 0 then H.YtdBal03
     when H.YtdBal02  > 0 then H.YtdBal02
     when H.YtdBal01 > 0 then H.YtdBal01
     when H.YtdBal00 > 0 then H.YtdBal00
END)
from AcctHist H 
join Account A
    On A.Acct = H.Acct
JOIN PSSFAAssetClass C
    on (H.Acct = C.Acct or H.Acct  = C.AccDeprAcct) 
where FiscYr = 2013
group by CpnyID, H.Acct, A.Descr
order by CpnyID, H.Acct;

我还修复了join语法。