动态列动态到行 - 从最后一列

时间:2015-07-06 06:06:12

标签: mysql sql dynamic pivot

我有很多像下面这样的表,每个表的列名都不同。

id  city  aaaa  bbbb  cccc  dddd  eeee  ffff  gggg  hhhh  iiii  jjjj  kkkk  llll  mmmm   
--  ----  ----  ----  ----  ----  ----  ----  ----  ----  ----  ----  ----  ----  ----
1   LAX    0.0   0.0   1.0   2.5   0.0   3.0   0.0   0.0   1.0   0.0   1.6  0.0  1.1
2   SFO    1.7   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  0.0  2.4
3   NYC    0.0   1.0   0.0   0.0   4.0   0.0   0.0   0.0   0.0   2.0   0.0  0.0  1.3

我想在上面的示例表中获得如下结果:

id city item  qty
-- ---- ----  ----
1  LAX  cccc   1.0
1  LAX  dddd   2.5
1  LAX  ffff   3.0
1  LAX  iiii   1.0
1  LAX  kkkk   1.6
1  LAX  mmmm   1.1  (missing from result)
2  SFO  aaaa   1.7
2  SFO  mmmm   2.4  (missing from result)
3  NYC  bbbb   1.0
3  NYC  eeee   4.0
3  NYC  jjjj   2.0
3  NYC  mmmm   1.3  (missing from result)

我试图从下面的链接修改查询,但我无法获取所有记录。它只返回9条记录,并从列< llll'和' mmmm'。我试过不同的表,但它收集到前10列。我理解基本的SQL,但这太复杂了,无法解决。请帮帮我!

Transposing Dynamic Columns to Rows


    (Copied from above link page and I modified a little)

    SET @sql = NULL;
    SELECT
    GROUP_CONCAT(DISTINCT
    CONCAT(
        'select id, city, ''',
        c.column_name,
        ''' as item, ',
        c.column_name,
        ' as qty 
        from test1
        where ',
        c.column_name,
        ' > 0'
        ) SEPARATOR ' UNION ALL '
    ) INTO @sql
    FROM information_schema.columns c
    where c.table_name = 'test1'
        and c.column_name not in ('id','city')
    order by c.ordinal_position;

    SET @sql 
        = CONCAT('select id, city, item, qty
        from
        (', @sql, ') x  order by id');

    PREPARE stmt FROM @sql;
    EXECUTE stmt;

0 个答案:

没有答案