MySQL動態行轉列操作
問題:
從多個表中檢索數據,並將其格式化為動態列標題的透視表,即使事先不知道確切的列數。
原始查詢:
<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>
使用CASE語句的解決方案:
MySQL沒有PIVOT函數,因此需要使用帶有CASE語句的聚合函數:
<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>
使用預處理語句的動態透視表:
為了處理動態列標題,可以使用預處理語句:
<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>
以上是如何將MySQL旋轉到列中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!