問題:
將一個包含三列的表轉換為一個數據透視表,其中行變為列。
示例:
輸入表:
hostid | itemname | itemvalue |
---|---|---|
1 | A | 10 |
1 | B | 3 |
2 | A | 9 |
2 | C | 40 |
所需輸出(數據透視表):
hostid | A | B | C |
---|---|---|---|
1 | 10 | 3 | 0 |
2 | 9 | 0 | 40 |
解決方案:
MySQL 的數據透視功能涉及一個三步過程:
<code class="language-sql">SELECT hostid, itemname, itemvalue FROM history;</code>
添加與每個唯一 itemname 對應的列。
<code class="language-sql">CREATE VIEW history_extended AS ( SELECT history.*, CASE WHEN itemname = "A" THEN itemvalue END AS A, CASE WHEN itemname = "B" THEN itemvalue END AS B, CASE WHEN itemname = "C" THEN itemvalue END AS C FROM history );</code>
按 hostid 分組,並對每一列的值求和。
<code class="language-sql">CREATE VIEW history_itemvalue_pivot AS ( SELECT hostid, SUM(A) AS A, SUM(B) AS B, SUM(C) AS C FROM history_extended GROUP BY hostid );</code>
<code class="language-sql">CREATE VIEW history_itemvalue_pivot_pretty AS ( SELECT hostid, COALESCE(A, 0) AS A, COALESCE(B, 0) AS B, COALESCE(C, 0) AS C FROM history_itemvalue_pivot );</code>
注意事項和限制:
以上是如何在 MySQL 中透視表:將行轉換為列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!