mysql 有pivot
时间: 2023-10-16 07:22:45 浏览: 150
MySQL并没有Pivot操作,但可以使用CASE WHEN语句进行数据透视,实现类似Pivot的功能。具体方法如下:
假设有以下数据表:
```
+----+------+---------+
| id | name | score |
+----+------+---------+
| 1 | Tom | 90 |
| 1 | Tom | 80 |
| 2 | Jack | 70 |
| 2 | Jack | 60 |
| 3 | Lucy | 100 |
| 3 | Lucy | 95 |
+----+------+---------+
```
现在需要将上表转化为以下形式:
```
+----+------+--------+--------+--------+
| id | name | score1 | score2 | score3 |
+----+------+--------+--------+--------+
| 1 | Tom | 90 | 80 | null |
| 2 | Jack | 70 | 60 | null |
| 3 | Lucy | 100 | 95 | null |
+----+------+--------+--------+--------+
```
可以使用下面的SQL语句实现:
```
SELECT
id,
name,
MAX(CASE WHEN rn = 1 THEN score END) AS score1,
MAX(CASE WHEN rn = 2 THEN score END) AS score2,
MAX(CASE WHEN rn = 3 THEN score END) AS score3
FROM (
SELECT
id,
name,
score,
ROW_NUMBER() OVER(PARTITION BY id ORDER BY name) AS rn
FROM table_name
) AS t
GROUP BY id, name;
```
其中,ROW_NUMBER()函数用于对每个id进行排序,生成rn列,然后使用CASE WHEN语句将rn列的值作为列名,将score填充到相应的位置。最后使用GROUP BY语句将结果按照id和name进行分组。
阅读全文