Unpivot dynamic columns to rows - missing data fro

2019-07-10 18:51发布

问题:

I have many tables like below, and column names are different each table.

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

And I would like to get result like below for above example table:

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)

I have tried to modify query from below link, but I cannot get all records. It returns only 9 records, and missing data from column 'llll' and 'mmmm'. I have tried with different table, but it gathered up to first 10 columns. I understand basic SQL, but this is too complex to solve. Please help me!

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;