34,594
社区成员
发帖
与我相关
我的任务
分享
select 姓名,
sum(case 课程 when '语文' then 分数 else 0 end) as 语文,
sum(case 课程 when '数学' then 分数 else 0 end) as 数学,
sum(case 课程 when '物理' then 分数 else 0 end) as 物理,
cast(sum(分数)as decimal(18,2))as 总分,
cast(AVG(分数)as decimal(18,2))as 平均分
from tb
group by 姓名
你用这种写法。。。。create table tb(姓名 varchar(10),课程 varchar(10),分数 int)
insert into tb values('张三','语文',74)
insert into tb values('张三','数学',83)
insert into tb values('张三','物理',93)
insert into tb values('李四','语文',74)
insert into tb values('李四','数学',84)
insert into tb values('李四','物理',94)
go
select * from tb
go
select m.*,n.总分,n.平均分
from
(
select * from tb pivot(max(分数)for 课程 in(语文,数学,物理))a
)m,
(
select 姓名,sum(分数)总分,cast(avg(分数*1.0)as decimal(18,2))平均分
from tb group by 姓名
)n where m.姓名=n.姓名
姓名 语文 数学 物理 总分 平均分
---------- ----------- ----------- ----------- ----------- ---------------------------------------
李四 74 84 94 252 84.00
张三 74 83 93 250 83.33
(2 行受影响)