--临时表知识多了一个#标示符 并且关闭连接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
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