【SQLSERVER】行转列方法

数据库建表

create table student 
(id int identity(1,1) primary key,
name nvarchar(20),
subject_id int,
score int,
grade varchar(10)
)

insert into student(name,subject_id,score,grade)values('张三',1,90,'A')
insert into student(name,subject_id,score,grade)values('张三',2,75,'B')
insert into student(name,subject_id,score,grade)values('李四',1,70,'B')
insert into student(name,subject_id,score,grade)values('李四',2,88,'B')
insert into student(name,subject_id,score,grade)values('王五',1,65,'C')
insert into student(name,subject_id,score,grade)values('王五',2,65,'C')

select * from student

在这里插入图片描述

1 使用聚合函数巧妙解决,可以用max、sum等

select name,
	max(case when subject_id=1 then score else 0 end) as Chinese,
	max(case when subject_id=2 then score else 0 end) as math
from student 
group by name

在这里插入图片描述

2 使用pivot函数

select name,
	max([1]) as Chinese,
	max([2]) as math
from student  pivot(max(score) for subject_id in ([1],[2]))t
group by name

在这里插入图片描述
3.行转列,多列,参考

--1
select name,
	max(case when subject_id=1 then score else 0 end) as Chinese,
	max(case when subject_id=1 then grade else null end) as Chinese_g,
	max(case when subject_id=2 then score else 0 end) as math,
    max(case when subject_id=2 then grade else null end) as math_g
from student 
group by name;
--2
with A as 
(select name,
	max([1]) as Chinese,
	max([2]) as math
from student  
pivot(max(score) for subject_id in ([1],[2])
)t
group by name),
B as(
select name,
	max([1]) as Chinese_g,
	max([2]) as math_g
from student  
pivot(max(grade) for subject_id in ([1],[2])
)t
group by name)
select a.name,Chinese,Chinese_g,math,math_g from  A,B where A.name=b.name 
--3
select name,Chinese,max([1]) as Chinese_g,math,max([2]) as math_g
	from student 
	inner join 
	(select name as namea,max([1]) as Chinese,max([2]) as math from student  
	pivot(max(score) for subject_id in ([1],[2]))t 
	group by name) st on student.name=st.namea
	pivot(max(grade) for subject_id in ([1],[2]))ss
 group by name,Chinese,math

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寒冰的暖

谢谢您的赞许投喂~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值