加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sqlserver 行转列

发布时间:2020-12-12 13:38:10 所属栏目:MsSql教程 来源:网络整理
导读:1.先建张测试的表吧 if object_id('tb')is not null drop table tbgocreate table tb(name varchar(10),kecheng varchar(10),fenshu int)insert into tb values('张三','语文',74)insert into tb values('张三','数学',83)insert into tb values('张三','物

1.先建张测试的表吧

if object_id('tb')is not null drop table tb
go
create table tb(name varchar(10),kecheng varchar(10),fenshu int)
insert into tb values('张三','语文',74)
insert into tb values('张三','数学',83)
insert into tb values('张三','物理',93)
insert into tb values('李四',74)
insert into tb values('李四',84)
insert into tb values('李四',94)
insert into tb values('李四',94)
go
select*from tb
go

2.行转列的方法(第一种)

select name as 姓名,max(case kecheng when'语文' then fenshu else 0 end)语文,max(case kecheng when'数学' then fenshu else 0 end)数学,max(case kecheng when'物理' then fenshu else 0 end)物理

from tb

group by name
3.行转列的方法(第二种)

select name as 姓名,语文,数学,物理 from tb
pivot
 (
sum(fenshu) for kecheng in(语文,物理)
) as b

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读