將 MySQL 欄位資料轉換為行格式(透視表)
本文介紹如何將包含多列資料的 MySQL 表轉換為行和列格式的資料。產生的結構稱為透視表,它提供了一種簡潔而全面的資料視圖。
問題陳述:
我們有一個包含多列的表,每列代表一個資料類別,我們的目標是將其轉換為透視表格式,其中行代表類別(col1、col2、col3、col4),列代表月份(Jan 、Feb)。
解決方案架構:
要在 MySQL 中實現此轉換,我們必須遵循以下兩步驟流程:
反透視 (UNION ALL):
透視 (聚合和 CASE):
已實現的查詢:
反透視 (UNION ALL):
<code class="language-sql">SELECT id, month, col1 AS value, 'col1' AS descrip FROM yourtable UNION ALL SELECT id, month, col2 AS value, 'col2' AS descrip FROM yourtable UNION ALL SELECT id, month, col3 AS value, 'col3' AS descrip FROM yourtable UNION ALL SELECT id, month, col4 AS value, 'col4' AS descrip FROM yourtable;</code>
透視 (聚合和 CASE):
<code class="language-sql">SELECT descrip, MAX(CASE WHEN month = 'Jan' THEN value ELSE 0 END) AS Jan, MAX(CASE WHEN month = 'Feb' THEN value ELSE 0 END) AS Feb FROM ( SELECT id, month, col1 AS value, 'col1' AS descrip FROM yourtable UNION ALL SELECT id, month, col2 AS value, 'col2' AS descrip FROM yourtable UNION ALL SELECT id, month, col3 AS value, 'col3' AS descrip FROM yourtable UNION ALL SELECT id, month, col4 AS value, 'col4' AS descrip FROM yourtable ) AS source GROUP BY descrip;</code>
結果:
此查詢會將輸入表轉換為透視表格式:
DESCRIP | Jan | Feb |
---|---|---|
col1 | A | C |
col2 | B | A |
col3 | 0 | G |
col4 | B | E |
以上是如何將 MySQL 列資料轉換為基於行的資料透視表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!