如何根据表中的组创建新列?

时间:2014-01-24 07:45:37

标签: mysql

通过使用mysql我可以根据表中的组创建新列吗?我只能获得分组和group_concat。

Before
-------------------------
no  |  item   |   code  |
-------------------------
1   |   aa    |    x    |
2   |   cc    |    c    |
3   |   pfr   |    a    |
4   |   bog   |         |
5   |   aa    |    x    |
6   |   pfr   |    x    |
1   |   aa    |    x    |
6   |   pfr   |    a    |
-------------------------
After group and group_concat
-------------------------
no  |  item   |   code  |
-------------------------
1   |   aa    |   x-2   |
2   |   cc    |   c-1   |
3   |   pfr   |   a-1   |
4   |   bog   |         |
5   |   aa    |   x-1   |
6   |   pfr   | a-1,x-1 |
-------------------------
I want to make like below this. Is it possible?
-------------------------------------------------------------------------------------
no  | aa_qty | aa_code | cc_qty | cc_code | pfr_qty | pfr_code | bog_qty | bog_code |
-------------------------------------------------------------------------------------
1   |   2    |   x-2   |        |         |         |          |         |          |
2   |        |         |   1    |   c-1   |         |          |         |          |
3   |        |         |        |         |    1    |   a-1    |         |          |
4   |        |         |        |         |         |          |    1    |          |
5   |   1    |   x-1   |        |         |         |          |         |          |
6   |        |         |        |         |    2    | a-1,x-1  |         |          |
-------------------------------------------------------------------------------------

1 个答案:

答案 0 :(得分:0)

您可以使用Pivot Table机制实现此目的。 MySQL对此机制没有直接支持。您需要依赖各种if .. else..case .. when ...语句来构建所需的结果视图。

在给出的示例数据中,例如在表item_codes中,noitemcode作为列,您可以尝试以下示例。

select no,
    case item when 'aa' then cnt else '' end as aa_qty,
    case item when 'aa' then code else '' end as aa_code,
    case item when 'cc' then cnt else '' end as cc_qty,
    case item when 'cc' then code else '' end as cc_code,

    case item when 'pfr' then cnt else '' end as pfr_qty,
    case item when 'pfr' then code else '' end as pfr_code,
    case item when 'bog' then cnt else '' end as bog_qty,
    case item when 'bog' then code else '' end as bog_code
from
    (
        select no, item, sum(cnt) cnt, group_concat( code ) code
        from
            (
                select
                     no, item, count(no) cnt,
                     if( code='', code, concat( code, '-', count(no) ) ) 'code'
                from item_codes ic
                group by ic.no, ic.item, ic.code
            ) ig group by no, item
    ) grouped_data;

您可能需要根据数据差异和其他事件(如空值和空码等)进行一些更改。