Setting column values as column names in the SQL query result
What you are attempting to do is a PIVOT
MySQL does not have a PIVOT
function so you can replicate this using a CASE
and an aggregate function.
If you have a known number of columns, then you can use a static version and hard-code the values. Similar to this (See SQL Fiddle with demo):
select id,
max(case when col1='name' then col2 end) name,
max(case when col1='name2' then col2 end) name2,
max(case when col1='name3' then col2 end) name3
from yourtable
group by id
But if you have an unknown number of columns, then you can use a prepared statement and create this dynamically:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when col1 = ''',
col1,
''' then col2 end) AS ',
col1
)
) INTO @sql
FROM yourtable;
SET @sql = CONCAT('SELECT id, ', @sql, '
FROM yourtable
GROUP BY id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
See SQL Fiddle with Demo
This is done with a pivot table. Grouping by id
, you issue CASE
statements for each value you want to capture in a column and use something like a MAX()
aggregate to eliminate the nulls and collapse down to one row.
SELECT
id,
/* if col1 matches the name string of this CASE, return col2, otherwise return NULL */
/* Then, the outer MAX() aggregate will eliminate all NULLs and collapse it down to one row per id */
MAX(CASE WHEN (col1 = 'name') THEN col2 ELSE NULL END) AS name,
MAX(CASE WHEN (col1 = 'name2') THEN col2 ELSE NULL END) AS name2,
MAX(CASE WHEN (col1 = 'name3') THEN col2 ELSE NULL END) AS name3
FROM
yourtable
GROUP BY id
ORDER BY id
Here's a working sample
Note: This only works as is for a finite and known number of possible values for col1
. If the number of possible values is unknown, you need to build the SQL statement dynamically in a loop.