sqlServer:行列转换之多行转一行

记得在刚进项目组时候,使用oracle数据库,遇到的第一个难题就是行列转换,哈哈,真是菜的一BI,现在使用sqlServer数据库,又遇到了,记录一下,以备后用和帮助后来者。

言归正传:

数据库:sqlServer2008R2 英文版

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 ;

 

4.其他待补充

 

转载于:https://www.cnblogs.com/zhengzeze/p/5584428.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值