CREATE TABLE `stuscore` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`subject` varchar(50) DEFAULT NULL,
`score` bigint(20) DEFAULT NULL,
`stuid` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8
insert into test.stuscore(name,subject,score,stuid) values ('张三','数学',89,1);
insert into test.stuscore(name,subject,score,stuid) values ('张三','语文',80,1);
insert into test.stuscore(name,subject,score,stuid) values ('张三','英语',70,1);
insert into test.stuscore(name,subject,score,stuid) values ('李四','数学',90,2);
insert into test.stuscore(name,subject,score,stuid) values ('李四','语文',70,2);
insert into test.stuscore(name,subject,score,stuid) values ('李四','英语',80,2);
select
stuid 学号,
name 姓名,
(case when subject = '语文' then score else 0 end )as 语文,
(case when subject = '数学' then score else 0 end )as 数学,
(case when subject = '英语' then score else 0 end )as 英语
from
stuscore
group by
stuid,
name
order by
总分;
方式二
select
stuid 学号,
name 姓名,
max(case when subject = '语文' then score else 0 end )as 语文,
max(case when subject = '数学' then score else 0 end )as 数学,
max(case when subject = '英语' then score else 0 end )as 英语,
max(score) 最高分,
SUM(score)总分,
avg(score)平均分
from
stuscore
group by
stuid,
name
order by
总分;