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>
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>
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>
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!