Home > Database > Mysql Tutorial > How to Unpivot and Pivot Data in MySQL to Transform Columns into Rows?

How to Unpivot and Pivot Data in MySQL to Transform Columns into Rows?

DDD
Release: 2025-01-09 15:07:41
Original
987 people have browsed it

How to Unpivot and Pivot Data in MySQL to Transform Columns into Rows?

MySQL data pivot and pivot: convert columns into rows

Suppose you have a table with multiple columns (col1, col2, col3, etc.) and want to convert it to a pivot table format, presenting the data in row units rather than columns.

To achieve this in MySQL, first use the UNION ALL query to pivot the data. This process creates multiple rows from the original column values:

SELECT id, month, col1 AS value, 'col1' AS descrip
FROM yourtable
UNION ALL
SELECT id, month, col2 AS value, 'col2' AS descrip
FROM yourtable
UNION ALL
SELECT id, month, col3 AS value, 'col3' AS descrip
FROM yourtable
UNION ALL
SELECT id, month, col4 AS value, 'col4' AS descrip
FROM yourtable;
Copy after login

UNION ALL Query results:

IDMONTHVALUEDESCRIP
101JanAcol1
102febCcol1
101JanBcol2
102febAcol2
101Jan(null)col3
102febGcol3
101JanBcol4
102febEcol4

Next, wrap the UNION ALL query in a subquery to pivot the data. Use aggregate functions GROUP BY and CASE statements to convert the structure of the unpivoted perspective into the desired perspective format:

SELECT descrip,
MAX(CASE WHEN month = 'jan' THEN value ELSE 0 END) AS jan,
MAX(CASE WHEN month = 'feb' THEN value ELSE 0 END) AS feb
FROM (
    SELECT id, month, col1 AS value, 'col1' AS descrip
    FROM yourtable
    UNION ALL
    SELECT id, month, col2 AS value, 'col2' AS descrip
    FROM yourtable
    UNION ALL
    SELECT id, month, col3 AS value, 'col3' AS descrip
    FROM yourtable
    UNION ALL
    SELECT id, month, col4 AS value, 'col4' AS descrip
    FROM yourtable
) AS src
GROUP BY descrip;
Copy after login

Results of pivot query:

DESCRIP JAN FEB
col1 A C
col2 B A
col3 0 G
col4 B E

This process effectively converts the table structure from columns to rows, allowing you to present your data in a more concise and clear way.

The above is the detailed content of How to Unpivot and Pivot Data in MySQL to Transform Columns into Rows?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template