Home > Database > Mysql Tutorial > How to Perform Row to Column Transformation (Pivot) in MySQL with Dynamic Data?

How to Perform Row to Column Transformation (Pivot) in MySQL with Dynamic Data?

Mary-Kate Olsen
Release: 2024-11-28 11:51:10
Original
955 people have browsed it

How to Perform Row to Column Transformation (Pivot) in MySQL with Dynamic Data?

Row to Column Transformation in MySQL: Pivot Table for Dynamic Data

Pivot tables are a convenient way to transform data from a row-oriented format to a column-oriented format, allowing for easier analysis and reporting. In MySQL, this transformation can be achieved through a specialized technique.

Consider the following example data:

ID Type Email Degignation
1000000000 202 [email protected] Entrepreneur
1000000000 234 [email protected] Engineering,Development
1000000000 239 [email protected] CTO

To pivot this data, we utilize the following query:

SELECT ID, 
 MAX(CASE Type WHEN 202 THEN Degignation END) AS `202`
 MAX(CASE Type WHEN 234 THEN Degignation END) AS `234`
 MAX(CASE Type WHEN 239 THEN Degignation END) AS `239`
 Email
FROM mytable
GROUP BY ID, Email
Copy after login

This query employs the CASE expression to dynamically create columns for each distinct Type value. The MAX function is used to aggregate the Degignation values for each ID and Email combination.

It's important to note that for this query to work effectively, you must know all the possible Type values beforehand. MySQL does not allow dynamic addition of columns based on data discovered at runtime; column definitions must be static during query preparation.

This technique allows you to transform row-oriented data into a column-oriented format, facilitating analysis and reporting tasks by providing a more intuitive data presentation.

The above is the detailed content of How to Perform Row to Column Transformation (Pivot) in MySQL with Dynamic Data?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template