2014-09-30 77 views
0

這可能是一個非常基本的問題,但我試圖給出一個給定月份的訂單總值的直方圖(不包括運費&稅)。SQL選擇與SUM的情況?

不幸的是表中沒有列的總數,所以它需要從小計減去任何折扣或應用信用計算。

我認爲這樣的事情可能會奏效,但我不認爲SUM表達式在case語句中被正確計算,因爲它只返回「else」條件。

select t.range as [price range], COUNT(*) as [orders] 
from (
    select case 
     when SUM(o.subtotal - o.discount - o.credit) between 0 and 49.99 then '0-49.99' 
     when SUM(o.subtotal - o.discount - o.credit) between 50 and 99.99 then '50-99.99' 
     when SUM(o.subtotal - o.discount - o.credit) between 100 and 149.99 then '100-149.99' 
     when SUM(o.subtotal - o.discount - o.credit) between 150 and 199.99 then '150-199.99' 
     else '200+' end as range 
    from dbo.[order] o 
    where o.date_placed BETWEEN '4/1/14' AND '4/30/14') t 
group by t.range 

我在做什麼錯?這是在MS SQL Server btw。

回答

1

這應該工作:

select t.range as [price range], COUNT(*) as [orders] 
from (
    select case 
     when (o.subtotal - o.discount - o.credit) between 0 and 49.99 then '0-49.99' 
     when (o.subtotal - o.discount - o.credit) between 50 and 99.99 then '50-99.99' 
     when (o.subtotal - o.discount - o.credit) between 100 and 149.99 then '100-149.99' 
     when (o.subtotal - o.discount - o.credit) between 150 and 199.99 then '150-199.99' 
     else '200+' end as range 
    from dbo.[order] o 
    where o.date_placed BETWEEN '4/1/14' AND '4/30/14') t 
group by t.range 
+0

感謝 - 沒有意識到這只是一個簡單的語法錯誤。這對我有效。 – dekaliber 2014-09-30 19:27:06

2

試試這個格式爲你的情況statmenets

select 
    sum(case when o.subtotal - o.discount - o.credit between 0 and 49.99 then 1 else 0 end) as bucket1, 
    sum(case when o.subtotal - o.discount - o.credit between 50 and 99.99 then 1 else 0 end) as bucket2, 
    sum(case when o.subtotal - o.discount - o.credit between 100 and 149.99 then then 1 else 0 end) as bucket3, 
    sum(case when o.subtotal - o.discount - o.credit between 150 and 199.99 then 1 else 0 end) as bucket4, 
    sum(case when o.subtotal - o.discount - o.credit >= 200 then 1 else 0 end) as bucket5 
0

你可以做一個查詢中所有這一切工作了。實際上不需要子查詢來做到這一點。

select 
    case SUM(o.subtotal - o.discount - o.credit) 
     when between 0 and 49.99 then '0-49.99' 
     when between 50 and 99.99 then '50-99.99' 
     when between 100 and 149.99 then '100-149.99' 
     when between 150 and 199.99 then '150-199.99' 
     else '200+' end 
    as PriceRange 
    , COUNT(*) as [orders] 
from dbo.[order] o 
where o.date_placed BETWEEN '4/1/14' AND '4/30/14' 
group by case SUM(o.subtotal - o.discount - o.credit) 
    when between 0 and 49.99 then '0-49.99' 
    when between 50 and 99.99 then '50-99.99' 
    when between 100 and 149.99 then '100-149.99' 
    when between 150 and 199.99 then '150-199.99' 
    else '200+' end