MySQL 数据透视:将列转换为行
MySQL 中,需要通过将列转换为行来生成透视表,以便更好地呈现数据。例如,考虑一个表,其中包含多个列(例如,col1、col2),代表不同月份的数据(例如,一月、二月)。
需求: 创建一个以透视表格式呈现数据的报表,其中每一行代表原始表中的一列,每一列代表不同的月份。
数据展开:
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>
结果:
此查询将数据转换为以下格式:
ID | MONTH | VALUE | DESCRIP |
---|---|---|---|
101 | Jan | A | col1 |
101 | Jan | B | col2 |
101 | Jan | NULL | col3 |
101 | Jan | B | col4 |
102 | Feb | C | col1 |
102 | Feb | A | col2 |
102 | Feb | G | col3 |
102 | Feb | E | col4 |
数据透视:
数据展开后,可以使用聚合函数将其转换为所需的透视表格式。以下查询使用 CASE 语句按每列 (descrip) 分组数据,并显示一月和二月的值:
<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 ) src GROUP BY descrip</code>
结果:
此查询生成所需的透视表格式:
DESCRIP | JAN | FEB |
---|---|---|
col1 | A | C |
col2 | B | A |
col3 | 0 | G |
col4 | B | E |
以上是如何在 MySQL 中透视数据:将列转换为行?的详细内容。更多信息请关注PHP中文网其他相关文章!