sqlServer:行列转换之多行转一行
- 作者: 五速梦信息网
- 时间: 2026年04月04日 13:26
1.建表:学生表(姓名,学科,成绩)
CREATE TABLE teststudent(
stuname varchar(50) NULL,
subjects varchar(50) NULL,
source int NULL
)
drop table teststudent ;
select * from teststudent ;
delete from teststudent ;
2.准备数据:
insert into teststudent(stuname,subjects,source) values('小明','语文',80);
insert into teststudent(stuname,subjects,source) values('小明','数学',85);
insert into teststudent(stuname,subjects,source) values('小明','英语',90);
insert into teststudent(stuname,subjects,source) values('小红','语文',86);
insert into teststudent(stuname,subjects,source) values('小红','数学',90);
insert into teststudent(stuname,subjects,source) values('小红','英语',85);
insert into teststudent(stuname,subjects,source) values('小亮','语文',99);
insert into teststudent(stuname,subjects,source) values('小亮','数学',99);
insert into teststudent(stuname,subjects,source) values('小亮','英语',100);
3.转换:可以采用max()、sum()两种方式
--方式1:
select stuname ,
MAX(case when subjects = '语文' then source else 0 end ) '语文',
MAX(case when subjects = '数学' then source else 0 end ) '数学',
MAX(case when subjects = '英语' then source else 0 end ) '英语'
from teststudent group by stuname ;
--方式2:
select stuname ,
SUM(case when subjects = '语文' then source else 0 end) '语文',
SUM(case when subjects = '数学' then source else 0 end ) '数学',
SUM(case when subjects = '英语' then source else 0 end ) '英语'
from teststudent group by stuname ;
相关文章
-
Sqlserver2005附加数据库时出错提示操作系统错误5(拒绝访问)错误5120的解决办法
Sqlserver2005附加数据库时出错提示操作系统错误5(拒绝访问)错误5120的解决办法
- 互联网
- 2026年04月04日
-
sqlserver2008r2维护计划
sqlserver2008r2维护计划
- 互联网
- 2026年04月04日
-
SqlServer把日期转换成不同格式的字符串的函数大全
SqlServer把日期转换成不同格式的字符串的函数大全
- 互联网
- 2026年04月04日
-
sqlserver 身份证号推算生日
sqlserver 身份证号推算生日
- 互联网
- 2026年04月04日
-
SQLserver 获取dbo的表名
SQLserver 获取dbo的表名
- 互联网
- 2026年04月04日
-
SQLServer 各版本区别
SQLServer 各版本区别
- 互联网
- 2026年04月04日






