create table #tmp
(
name nvarchar(50),
[subject] nvarchar(50),
grade float
)
insert into #tmp values('张三' ,'语文',90)
insert into #tmp values('张三' ,'数学',80)
insert into #tmp values('张三' ,'英语',75)
insert into #tmp values('李四' ,'语文',75)
insert into #tmp values('李四' ,'数学',60)
insert into #tmp values('李四' ,'英语',85)
insert into #tmp values('王五' ,'语文',85)
insert into #tmp values('王五' ,'数学',77)
insert into #tmp values('王五' ,'英语',99)
select * from #tmp;
select name as 姓名,
AVG(case when [subject]='语文' then grade end) as 语文,
AVG(case when [subject]='数学' then grade end) as 数学,
AVG(case when [subject]='英语' then grade end) as 英语
from #tmp
group by #tmp.name
create table #tmp2 --添加物理、化学
(
姓名 nvarchar(50),
物理 float,
化学 float
)
insert into #tmp2 values('张三' ,75,80)
insert into #tmp2 values('李四' ,95,85)
insert into #tmp2 values('王五' ,90,85)
select * from #tmp2;
select a.姓名,a.语文,a.数学,a.英语,b.物理,b.化学 from (
select name as 姓名,
AVG(case when [subject]='语文' then grade end) as 语文,
AVG(case when [subject]='数学' then grade end) as 数学,
AVG(case when [subject]='英语' then grade end) as 英语
from #tmp
group by #tmp.name) a left join #tmp2 b on a.姓名=b.姓名