简体   繁体   English

计数和求和用例

[英]Count and SUM using case

I have table like this, name: Table.dbo 我有这样的表,名称: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

I wrote this query : 我写了这个查询:

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

How can I sum the Amount for the SM if the code is between 4 and 27 or the code is in (1,2,3) only (For example). 如果代码在4到27之间或代码仅在(1,2,3)中,我如何求和SM的金额(例如)。

Thank you very much! 非常感谢你!

Exactly like qxg said - Replace 就像qxg所说的-替换

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

with

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

If you want to total up amount for code between 4 and 27 or for codes 1,2,3 如果您要为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM