将 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中文网其他相关文章!