2017-10-18 151 views
0

我正在進行一些事務分析。 我希望看到每筆交易數量的交易量。 下面是數據和結果通緝。SQL SUM COUNT CASE

table name: trans_cust 

store_id trans_id product qty 
A   123  milk  1 
A   123 chocolate 1 
A   123 candy  1 
A   456 milk  4 
A   789 candy  1 
B   321 chocolate 3 
B   321 napkin  1 
B   654 blueberry 2 
C   987 candy  6 

Result 

Quantity num_Transaction 
1    1 
2    1 
3    1 
4+    3 

我有以下的嘗試,但它不工作。

select count(distinct(trans_id)) as num_transation, case 
when sum(quantity) = 1 then '1' 
when sum(quantity) = 2 then '2' 
when sum(quantity) = 3 then '3' 
when sum(quantity)>= 5 then '5+' else 'other' end as Quantity 

from (select sum(quantity) as Quantity from trans_cust) 

請問大家請幫忙嗎?謝謝。

+0

似乎是一個派生表是得心應手。 – jarlh

+0

你使用的是什麼版本的SQL? –

+0

蜂巢。上表是一個非常簡化的版本。謝謝。 – user8448815

回答

3

這是你想要的嗎?

SELECT CASE WHEN s.quantity >= 4 THEN '4+' 
      WHEN s.quantity = 1 THEN '1' 
      WHEN s.quantity = 2 THEN '2' 
      WHEN s.quantity = 3 THEN '3' 
     END as quantity 
     ,count(*) 
FROM (
    SELECT t.trans_id,sum(t.quantity) as quantity 
    FROM trans_cust t 
    group by t.trans_id) s 
GROUP BY CASE WHEN s.quantity >= 4 THEN '4+' 
      WHEN s.quantity = 1 THEN '1' 
      WHEN s.quantity = 2 THEN '2' 
      WHEN s.quantity = 3 THEN '3' 
     END 

使這一varchar列使代碼有點亂,你也可以這樣做:

SELECT p.quantity,count(*) FROM (
    SELECT CASE WHEN s.quantity >= 4 THEN '4+' 
       WHEN s.quantity = 1 THEN '1' 
       WHEN s.quantity = 2 THEN '2' 
       WHEN s.quantity = 3 THEN '3' 
      END as quantity 
    FROM (
     SELECT t.trans_id,sum(t.quantity) as quantity 
     FROM trans_cust t 
     group by t.trans_id) s) p 
GROUP BY p.quantity