使用大小写计数和SUM

时间:2015-11-05 07:00:00

标签: sql select case

我有这样的表,名称:Table.dbo

Amount  Desc    Month   SM  code    ID
$32,323.00  Bla1    1   121 3   2424221
$4,242.00   Bla2    1   A1  3   2424221
$3,535.00   Bla3    1   A3  1   3230824
$4,984.00   Bla4    1   433 1   3230824
$47,984.00  Bla5    1   B1  1   3230824
$3,472.00   Bla6    1   D2  27  2297429
$3,239.00   Bla7    1   124 27  2297429
$4,249.00   Bla8    1   114 24  3434334
$2,492.00   Bla9    1   132 24  3434334
$424.00     Bla10   2   232 3   2424221
$24,242.00  Bla7    2   124 3   2424221
$242,424    Bla4    2   433 1   3230824
$533.00     Bla13   2   235 1   3230824
$4,342.00   Bla14   2   223 1   3230824
$24,242.00  Bla15   2   224 27  2297429
$24,242.00  Bla1    2   121 27  2297429
$4,242.00   Bla17   2   432 24  3434334
$24,224.00  Bla9    2   132 24  3434334

我写了这个查询:

select 
[SM],
   count(*) as TotalCntOfSM,
   sum(case when [code] between 4 and 27 then 1 else 0 end) as TotalCntOfSM_R,
   sum(case when [code] in (1,2,3) then 1 else 0 end) as TotalCntOfSM_B,
   sum(case when [code] in (1) then 1 else 0 end) as TotalCntofSM_B1,
   sum(case when [code] in (2) then 1 else 0 end) as TotalCntofSM_B2,
   sum(case when [code] in (3) then 1 else 0 end) as TotalCntofSM_B3,
   sum([Amount]) As TotalAmount
   ****[How can I sum the Amount for the SM if the code is between 4 and 27?** For example]** 
from [Table]
group by [SM]
order by TotalCntOfSM desc

如果代码在4到27之间,或者代码仅在(1,2,3)中(例如),我该如何计算SM的金额。

非常感谢!

1 个答案:

答案 0 :(得分:0)

正如qxg所说 - 替换

****[How can I sum the Amount for the SM if the code is between 4 and 27?** For example]** `

sum(case when [code] between 4 and 27 then [Amount] else 0 end) as SMAmount

如果您希望总计4到27之间的代码金额或代码1,2,3

sum(case when [code] between 1 and 27 then [Amount] else 0 end) as SMAmount
You can write the above also as
sum(case when [code] between 4 and 27 OR [code] in (1,2,3) then [Amount] else 0 end) as SMAmount
相关问题