sql server 行转化成列数据 小结

--临时表知识多了一个#标示符  并且关闭连接sql后临时表会被数据库管理系统清除 除此外和正常无区别
create table #temp
(
 name varchar(12),
 course varchar(12),
 score int
)


insert into #temp values('学生1','语文',78);
insert into #temp values('学生1','数学',89);
insert into #temp values('学生1','英语',98);
insert into #temp values('学生2','语文',99);
insert into #temp values('学生2','数学',100);
insert into #temp values('学生2','英语',87);


select * from #temp


--需要max函数或者其他分组函数,视情况,要不然的话就加载group后面的字段,语法
select name,
max(case course when '语文' then score end) '语文' ,
max(case course when '数学' then score end) '数学' ,
max(case course when '英语' then score end) '英语' 
from #temp group by name


select name,
(case course when '语文' then score end) '语文' ,
(case course when '数学' then score end) '数学' ,
(case course when '英语' then score end) '英语' 
from #temp group by name,course,score


--使用行列转换函数pivot函数


select * from #temp pivot(max(score) for course in (语文,数学,英语)) a

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值