MySQL选择动态行值作为列名

时间:2016-03-15 10:55:08

标签: 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

如何设法从库存表中获取此输出?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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  

答案 2 :(得分: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

让我知道它的工作与否