記得在剛進項目組時候,使用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.其他待補充
