How can we write the SQL statement to pivot rows into c…
In MySQL, you can convert rows into columns using the following methods:
- Using CASE statements and aggregate functions:
SELECT
id,
MAX(CASE WHEN key = 'key1' THEN value END) AS value1,
MAX(CASE WHEN key = 'key2' THEN value END) AS value2,
MAX(CASE WHEN key = 'key3' THEN value END) AS value3
FROM
your_table
GROUP BY
id;
- Use the PIVOT function (supported in MySQL 8.0 and above):
SELECT
id,
value1,
value2,
value3
FROM
your_table
PIVOT (
MAX(value)
FOR key IN (key1, key2, key3)
) AS p;
These statements assume you have a table named “your_table” with columns id, key, and value. You will need to adjust them according to the actual table structure and data.