- 準備數據
- 建表
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);
- 原表數據
- 根據需求寫SQL
- 需求: 把原表數據統計如下
- SQL實現
方式一
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
總分;