【问题标题】:Count and SUM using case使用案例计数和求和
【发布时间】:2015-11-05 07:00:00
【问题描述】:

我有这样的表,名称: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 的金额。

非常感谢!

【问题讨论】:

  • 含义 4 和 27 之间是否包括?如果是的话,基本在1到27之间?
  • then SM替换then 1?
  • [SM] 列中有一些字符串值。计算 SUM([SM]) 时可以吗?
  • 您觉得我的回答有帮助吗?

标签: sql select case


【解决方案1】:

和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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-19
    • 2021-06-06
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多