Pivot rows into columns

倾然丶 夕夏残阳落幕 提交于 2020-01-06 14:57:36

问题


I have an SQL query that generates the following:

col1  | col2 | col3
=====================
item1 | key1 | value1
---------------------
item1 | key2 | value2

This is the query:

SELECT t1.col1, t2.col2, t2.col3
FROM table1 t1
JOIN table2 t2 ON t1.id = t1.table1_id

Data in table1:

id | col1
=========
1  | item1
2  | item1

Data in table2:

table1_id | col2 | col3
=====================
1         | key1 | item1
1         | key2 | item2
2         | key1 | item1
2         | key2 | item2
2         | key3 | item3

The number of rows is dynamic, so I could also get the following in some cases:

col1  | col2 | col3
=====================
item2 | key1 | value1
---------------------
item2 | key2 | value2
---------------------
item2 | key3 | value3

The way I want the first query to end up as is:

col1  | key1   | key2
=======================
item1 | value1 | value2

And the second query would be:

col1  | key1   | key2   | key3
==============================
item2 | value1 | value2 | value3

Is there an easy way to do this without over-complexing stuff? I am using MariaDB.


回答1:


I think you want this query:

SET SESSION group_concat_max_len = 1000000;

SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN t2.col2= ''',
      t2.col2,
      ''' THEN t2.col3 END) AS ',
      t2.col2
    )
   )INTO @sql
FROM  
     t1
JOIN  t2 ON t1.id = t2.table1_id
;


SET @sql=CONCAT('SELECT t1.col1, ',@sql,' FROM   
     t1
JOIN  t2 ON t1.id = t2.table1_id');

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

FIDDLE

If you have different items you probably want to group by item

FIDDLE



来源:https://stackoverflow.com/questions/27972461/pivot-rows-into-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!