问题:
将一个包含三列的表转换为一个数据透视表,其中行变为列。
示例:
输入表:
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中文网其他相关文章!