SQL语句行转列的几种通用方式以及延伸
在数据库开发中经常碰到行转列的问题,如下
select * from Scores
Student Subject Score
---------- ---------- -----------
张三 语文 74
张三 英语 83
李四 语文 74
李四 英语 84
王五 英语 94
王五 语文 93
需要转换为以下展示:
姓名 语文 英语
--------- --------- --------
张三 74 83
李四 74 84
王五 94 93
一般有两种通用的方法:
方法一:
select Student,
(select Score from Scores T where Subject='语文' and T.Student=Scores.Student) as '语文',
(select Score from Scores T where Subject='英语' and T.Student=Scores.Student) as '英语',
from Scores group by Student
方法二:
select Student as '姓名',
max(case Subject when '语文' then Score else 0 end) as '语文' ,
max(case Subject when '英语' then Score else 0 end ) as '英语'
from Scores
group by Student
延伸阅读
从这两种方式中可以看出,首先行转列最核心的是分组以及分组函数的使用。
