MySQL 資料解透視與透視:將列轉換為行
假設您有一個包含多個列(col1、col2、col3 等)的表,並且希望將其轉換為透視表格式,以行為單位而不是列來呈現資料。
在 MySQL 中實現此目標,首先使用 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>
UNION ALL
查詢的結果:
ID | MONTH | VALUE | DESCRIP |
---|---|---|---|
101 | Jan | A | col1 |
102 | feb | C | col1 |
101 | Jan | B | col2 |
102 | feb | A | col2 |
101 | Jan | (null) | col3 |
102 | feb | G | col3 |
101 | Jan | B | col4 |
102 | feb | E | col4 |
接下來,將 UNION ALL
查詢包裝在一個子查詢中以透視資料。使用聚合函數 GROUP BY
和 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 src GROUP BY descrip;</code>
透視查詢的結果:
DESCRIP | JAN | FEB |
---|---|---|
col1 | A | C |
col2 | B | A |
col3 | 0 | G |
col4 | B | E |
此程序有效地將表結構從列轉換為行,使您可以以更簡潔明了的方式呈現資料。
以上是如何在 MySQL 中逆透視和透視資料以將列轉換為行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!