2013-05-03 186 views
9

我想知道如何逆轉置Table_1Expected_Result_Table移調動態列到行

Table1 
----------------------------------------- 
Id  abc brt ccc ddq eee fff gga hxx 
----------------------------------------- 
12345  0 1 0 5 0 2 0 0 
21321  0 0 0 0 0 0 0 0 
33333  2 0 0 0 0 0 0 0 
41414  0 0 0 0 5 0 0 1 
55001  0 0 0 0 0 0 0 2 
60000  0 0 0 0 0 0 0 0 
77777  9 0 3 0 0 0 0 0 
Expected_Result_Table 
--------------------- 
Id  Word Qty>0 
--------------------- 
12345 brt 1 
12345 ddq 5 
12345 fff 2 
33333 abc 2 
41414 eee 5 
41414 hxx 1 
55001 hxx 2 
77777 abc 9 
77777 ccc 3 

那麼,如何轉列Table_1導致Expected_Result_Table,只考慮值> 0 ?

回答

19

MySQL沒有一個UNPIVOT功能,但是您可以將列轉換爲使用UNION ALL行。

的基本語法是:

select id, word, qty 
from 
(
    select id, 'abc' word, abc qty 
    from yt 
    where abc > 0 
    union all 
    select id, 'brt', brt 
    from yt 
    where brt > 0 
) d 
order by id; 

在你的情況,你的狀態,你需要動態列的解決方案。如果是這樣的話,那麼你將需要使用準備好的語句來生成動態SQL:

SET @sql = NULL; 

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

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


PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

SQL Fiddle with Demo

+0

嗨,bluefeet!你剛剛解決了這個問題。非常感謝! – 2013-05-06 13:29:06

+0

這是真棒..做魔術:) – UberNeo 2015-02-16 14:23:53

6

基本上,您可以將列中的數據轉化爲行,您可以使用UNION ALL。篩選器可以應用於未轉義的子查詢中,也可以單獨應用於部件。

select id, Word, Qty from 
(
    select id, 'abc' Word, abc Qty from table1 
    union all 
    select id, 'brt', brt from table1 
    union all 
    select id, 'ccc', ccc from table1 
    union all 
    select id, 'ddq', ddq from table1 
    union all 
    select id, 'eee', eee from table1 
    union all 
    select id, 'fff', fff from table1 
    union all 
    select id, 'gga', gga from table1 
    union all 
    select id, 'hxx', hxx from table1 
) x 
where Qty > 0 
order by id; 
+0

[SQL小提琴演示](http://sqlfiddle.com/#!2/ b0934/6/0) – RichardTheKiwi 2013-05-03 13:09:52

+0

謝謝,理查德。我的表格有動態和未知列。 – 2013-05-06 13:30:46