Setting column values as column names in the SQL query result
Problem Statement :
Output :
SQL Query :
SELECT
id,
MAX(CASE WHEN (col1 = 'Pending') THEN col2 ELSE NULL END) AS Pending,
MAX(CASE WHEN (col1 = 'Resolved') THEN col2 ELSE NULL END) AS Resolved
FROM
tableName
GROUP BY id
ORDER BY id
-- col1 matches the 'Pending' 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
id | col1 | col2 |
---|---|---|
1 | Pending | 30 |
1 | Resolved | 48 |
3 | Pending | 7 |
3 | Resolved | 1 |
4 | Pending | 11 |
4 | Resolved | 22 |
Output :
id | Pending | Resolved |
---|---|---|
1 | 30 | 48 |
3 | 7 | 1 |
4 | 11 | 22 |
SQL Query :
SELECT
id,
MAX(CASE WHEN (col1 = 'Pending') THEN col2 ELSE NULL END) AS Pending,
MAX(CASE WHEN (col1 = 'Resolved') THEN col2 ELSE NULL END) AS Resolved
FROM
tableName
GROUP BY id
ORDER BY id
-- col1 matches the 'Pending' 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