Home > Database > Mysql Tutorial > How to Dynamically Pivot MySQL Rows into Columns?

How to Dynamically Pivot MySQL Rows into Columns?

Mary-Kate Olsen
Release: 2025-01-25 13:12:16
Original
774 people have browsed it

How to Dynamically Pivot MySQL Rows into Columns?

MySQL dynamic row to column operation

Question:

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

Original query:

<code class="language-sql">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</code>
Copy after login

Solution using CASE statement:

MySQL does not have a PIVOT function, so you need to use an aggregate function with a CASE statement:

<code class="language-sql">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</code>
Copy after login

Dynamic pivot table using prepared statements:

To handle dynamic column headers, you can use prepared statements:

<code class="language-sql">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;</code>
Copy after login

The above is the detailed content of How to Dynamically Pivot MySQL Rows into Columns?. 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