| 姓名 | 科目 | 成绩 |
| 牛芬 | 语文 | 81 |
| 牛芬 | 数学 | 88 |
| 牛芬 | 英语 | 84 |
| 张三 | 语文 | 90 |
| 张三 | 数学 | 98 |
| 张三 | 英语 | 90 |
(表一)
现有一个表如(表一)
| 姓名 | 语文 | 数学 | 英语 |
| 牛芬 | 81 | 88 | 84 |
| 张三 | 90 | 98 | 90 |
想要转换为(表二)
sql:select stuName as 姓名,chinese as 语文,math as 数学,english as 英文 from(
select sutName,
case subject when chinese then score end as chinese,
case subject when math then score end as math,
case subject when english then score end as english
from table) as tmp
group by stuName
若要把(表二)转换成(表一)
postgresql里面有个unnest函数可以使用:
select stuName,unnest(array['chinese','math','english']) as subject,unnest(array[chinest,math,englist]) as score from table group by stuName
就这么简单
本文介绍如何使用SQL将宽表转换为长表及反向操作的方法。提供了具体的SQL语句示例,包括使用case when语句进行宽表到长表的转换,以及利用PostgreSQL的unnest函数实现长表到宽表的转换。
958

被折叠的 条评论
为什么被折叠?



