2013-02-10 50 views
2

我有一個表,看起來像這樣...分組相似的價值觀進入新的select語句

supplier_name status  count 
supplier_a  Unavailable 1 
supplier_a  Refunded  5 
supplier_a  Shipped  10 
supplier_z  Refunded  2 
supplier_z  Shipped  4 

我知道正是我想要的欄目,我想使用的值從第一個表返回值結構類似於以下...

supplier_name unavailable refunded shipped 
supplier_a  1    5   10 
supplier_z  0    2   4 

(注:在有特定列,應設置爲0,沒有值的情況下)

這將是可能的實現查詢?

回答

1

我覺得這樣的事情應該工作:

SELECT Supplier_Name, 
    MAX(CASE WHEN STATUS = 'Unavailable' THEN Count ELSE 0 END) as Unavailable, 
    MAX(CASE WHEN STATUS = 'Refunded' THEN Count ELSE 0 END) as refunded, 
    MAX(CASE WHEN STATUS = 'Shipped' THEN Count ELSE 0 END) as shipped 
FROM YourTable 
GROUP BY Supplier_Name 

這裏是SQL Fiddle

祝你好運。

+0

看起來非常好 – 2013-02-10 22:25:03

+0

@ mk_89 - 很高興我們可以幫忙! – sgeddes 2013-02-10 22:27:31

1

試試這個:

SELECT 
    supplier_name, 
    SUM(COALESCE(CASE WHEN status = 'unavailable' THEN `count` END, 0)) unavailable, 
    SUM(COALESCE(CASE WHEN status = 'refunded' THEN `count` END, 0)) refunded, 
    SUM(COALESCE(CASE WHEN status = 'shipped' THEN `count` END, 0)) shipped 
FROM tbl 
GROUP BY supplier_name 

SQL FIDDLE DEMO

+0

我毫不懷疑這個工程,但他們第一個答案工作正常 – 2013-02-10 22:25:43

+0

@ mk_89你有同一供應商的當前狀態不止一行? – 2013-02-10 23:04:05