"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Detailed explanation of MySQL dynamic row and column conversion skills

Detailed explanation of MySQL dynamic row and column conversion skills

Posted on 2025-05-02
Browse:148

How to Dynamically Pivot MySQL Rows into Columns?

MySQL dynamic row to column operation

]

question:

Retrieve data from multiple tables and format it as a pivot table for dynamic column titles, even if the exact number of columns is not known in advance.

Original query:

SELECT partners.name, products.name, COUNT(*) 
FROM sales
JOIN products ON sales.products_id = products.id
JOIN partners ON sales.partners_id = partners.id
GROUP BY sales.partners_id, sales.products_id
LIMIT 0, 30

Solution using CASE statement:

]

MySQL does not have a PIVOT function, so it is necessary to use an aggregate function with a CASE statement:

select pt.partner_name,
  count(case when pd.product_name = 'Product A' THEN 1 END) as ProductA,
  count(case when pd.product_name = 'Product B' THEN 1 END) as ProductB,
  count(case when pd.product_name = 'Product C' THEN 1 END) as ProductC,
  count(case when pd.product_name = 'Product D' THEN 1 END) as ProductD,
  count(case when pd.product_name = 'Product E' THEN 1 END) as ProductE
from partners pt
left join sales s
  on pt.part_id = s.partner_id
left join products pd
  on s.product_id = pd.prod_id
group by pt.partner_name

Dynamic pivot table using preprocessing statements:

]

To handle dynamic column headers, a preprocessing statement can be used:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'count(case when Product_Name = ''',
      Product_Name,
      ''' then 1 end) AS ',
      replace(Product_Name, ' ', '')
    )
  ) INTO @sql
from products;

SET @sql = CONCAT('SELECT pt.partner_name, ', @sql, ' from partners pt
left join sales s
  on pt.part_id = s.partner_id
left join products pd
  on s.product_id = pd.prod_id
group by pt.partner_name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3