MySQL Pivot: Rows to Columns Conversion

In MySQL, row to column and column to row transformations are typically achieved using the following methods:

  1. Performing row to column operation using aggregate functions and CASE statement.
SELECT
    MAX(CASE WHEN attribute = 'attribute1' THEN value END) AS attribute1,
    MAX(CASE WHEN attribute = 'attribute2' THEN value END) AS attribute2,
    MAX(CASE WHEN attribute = 'attribute3' THEN value END) AS attribute3
FROM your_table
GROUP BY id;
  1. Perform column-to-row operation using UNION ALL.
SELECT 'attribute1' AS attribute, attribute1 AS value FROM your_table
UNION ALL
SELECT 'attribute2' AS attribute, attribute2 AS value FROM your_table
UNION ALL
SELECT 'attribute3' AS attribute, attribute3 AS value FROM your_table;

These methods can be adjusted and expanded according to specific needs and data structures to achieve operations of converting rows into columns and columns into rows.

bannerAds