Mysql query to dynamically convert rows to columns
Solution 1:
You can use GROUP BY
and MAX
to simulate pivot. MySQL also supports IF
statement.
SELECT ID,
MAX(IF(`order` = 1, data, NULL)) data1,
MAX(IF(`order` = 2, data, NULL)) data2
FROM TableA
GROUP BY ID
- SQLFiddle Demo
If you have multiple values of order
, dynamic SQL may be more appropriate so that you will not have to modify the query:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(`order` = ', `order`, ',data,NULL)) AS data', `order`)
) INTO @sql
FROM TableName;
SET @sql = CONCAT('SELECT ID, ', @sql, '
FROM TableName
GROUP BY ID');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
- SQLFiddle Demo
- SQLFiddle Demo (Another example)
OUTPUT OF BOTH QUERIES:
╔════╦═══════╦═══════╗
║ ID ║ DATA1 ║ DATA2 ║
╠════╬═══════╬═══════╣
║ 1 ║ P ║ S ║
║ 2 ║ R ║ Q ║
╚════╩═══════╩═══════╝
Solution 2:
You need to use MAX
and GROUP BY
to simulate a PIVOT:
SELECT Id,
MAX(CASE WHEN Order = 1 THEN data END) data1,
MAX(CASE WHEN Order = 2 THEN data END) data2
FROM TableA
GROUP BY Id
And here is the SQL Fiddle.