2016-03-15 74 views
0

我在我的桌子下面的細節MySQL的選擇動態記錄的值作爲列名

股票表

id sale stock item_code branch 
1 0 200 abc  A 
2 100 200 abc  A 
3 0 200 def  B 
4 100 200 def  B 
5 0 200 xyz  B 
6 100 200 xyz  A 

而且,她是我的預期輸出:

item_code A-sale A-stock  B-sale B-stock 
abc   100  400  null  null 
def   null null  100  400 
xyz   100  200   0  200 

我怎麼能設法從股票表中獲得這個輸出?

回答

0

嘗試此查詢

SELECT 
    item_code, 
    SUM(CASE 
     WHEN branch = 'A' THEN sale 
     ELSE 0 
    END) 'A-sale', 
    SUM(CASE 
     WHEN branch = 'A' THEN stock 
     ELSE 0 
    END) 'A-stock', 
    SUM(CASE 
     WHEN branch = 'B' THEN sale 
     ELSE 0 
    END) 'B-sale', 
    SUM(CASE 
     WHEN branch = 'B' THEN stock 
     ELSE 0 
    END) 'B-stock' 
FROM 
    stock 
GROUP BY item_code 
+0

那相同的答案像我你只改變了語法了一下! – sagi

+0

嗨1000111謝謝你的回覆 – user3296668

+0

和薩吉你這種評論是相當幼稚的。這表明你只是爲了獲得聲望而渴望。我尊重他人的意見和價值觀,以及我對他人的期望。你很清楚不同的用戶可能會以幾乎相同的方式來處理這個問題。謝謝@ Sagi – 1000111

0
select item_code, 
    case when branch ='A' Then max(sale) end as A-sale, 
    case when branch ='A' Then sum(stock)as A-stock, 
    case when branch ='B' Then max(sale) end as B-sale, 
    case when branch ='B' Then sum(stock)as B-stock 
from table_name 
group by item_code 
0
SELECT 
    item_code, 
    SUM(CASE 
     WHEN branch = 'A' THEN sale 
     ELSE 0 
    END) 'A-sale', 
    SUM(CASE 
     WHEN branch = 'A' THEN stock 
     ELSE 0 
    END) 'A-stock', 
    SUM(CASE 
     WHEN branch = 'B' THEN sale 
     ELSE 0 
    END) 'B-sale', 
    SUM(CASE 
     WHEN branch = 'B' THEN stock 
     ELSE 0 
    END) 'B-stock' 
FROM 
    stock 
GROUP BY item_code 

讓我知道它的工作或沒有