Convert Rows into Columns in MySQL



Converting rows into columns also known as pivoting is a common requirement in SQL. Pivoting transforms data to present it in a more organized, user-friendly format, especially for reporting or analytics purposes. In this article, we'll explore the different methods available in MySQL to achieve this transformation.

Let's consider a sample table named sales:

Year Region Revenue
2021 North 5000
2021 South 3000
2022 North 7000
2022 South 4000

We may want to pivot this data to display the Region values as columns and show their corresponding Revenue for each year:

Year North South
2021 5000 3000
2022 7000 4000

Using Conditional Aggregation

The simplest way to pivot data in MySQL is to use CASE statements with an aggregation function like SUM() or MAX().

Query:

SELECT
Year, SUM(CASE WHEN Region = 'North' THEN Revenue ELSE 0 END) AS North,
    SUM(CASE WHEN Region = 'South' THEN Revenue
            ELSE 0 END) AS South FROM sales GROUP BY Year;

Output:

Year North South
2021 5000 3000
2022 7000 4000

Explanation:

  • CASE Statement: Checks the Region column for a specific value (e.g., 'North') and returns the Revenue if the condition is true; otherwise, it returns 0.

  • SUM() Function: Aggregates the Revenue for each region.

  • GROUP BY: Group the data by the Year column.

Using Dynamic SQL for Dynamic Pivoting

If the Region values are not fixed and we want the pivot to adjust dynamically based on the data we can use dynamic SQL. However, dynamic SQL is more complex and requires using prepared statements in MySQL.

  • Get Unique Column Values: Retrieve all unique regions to dynamically create the pivot columns.

  • Build the Query Dynamically: Construct the SQL query as a string.

  • Execute the Query: The Use prepared statements to execute the dynamically built query.


Example:

SET @sql = NULL;
--Generate column list dynamically SELECT GROUP_CONCAT(DISTINCT CONCAT(
    'SUM(CASE WHEN Region = ''', Region, ''' THEN Revenue ELSE 0 END) AS `',
    Region, '`')) INTO @sql FROM sales;
-- Construct the full query
SET @sql = CONCAT('SELECT Year, ', @sql, ' 
FROM sales 
GROUP BY Year');
-- Execute the query
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Explanation:

  • GROUP_CONCAT: Dynamically creates the SUM(CASE...) statements for all unique regions.

  • Prepared Statements: Allows MySQL to execute the dynamically constructed query.

Output:

Year North South
2021 5000 3000
2022 7000 4000

Conclusion

Converting rows into columns in MySQL or pivoting can be achieved using various methods depending on your use case and MySQL version. The simplest approach is using conditional aggregation with CASE statements but for dynamic requirements dynamic SQL or stored procedures are more appropriate.

Updated on: 2025-01-27T17:36:55+05:30

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements