SQL:用SQL統計學生成績 原來有這麼多玩法

  • 準備數據
  1. 建表

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
  1. 測試數據
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
  1. 需求: 把原表數據統計如下
    在這裏插入圖片描述
  2. 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
   總分;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章