2015-11-05 81 views
0

我有臺這樣的,名稱:Table.dbo計數和SUM使用情況

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 

我如何可以總結的金額爲SM如果代碼介於4到27之間,或者代碼僅在(1,2,3)中(例如)。

非常感謝!

+0

含義4和27之間是否包含?如果是,它基本上在1到27之間? –

+0

用'然後SM'替換'然後1'? – qxg

+0

[SM]列中有一些字符串值。計算SUM([SM])時可以嗎? –

回答

0

酷似QXG說 - 如果你想起來總代碼量之間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 

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

更換

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