“SQL 学生 课程 分数”的版本间的差异

来自姬鸿昌的知识库
跳到导航 跳到搜索
第30行: 第30行:
  
 
=== 查询总分最高的学生分数是多少 ===
 
=== 查询总分最高的学生分数是多少 ===
 +
先查最高分是多少<syntaxhighlight lang="sql">
 +
select student_id, sum(score)
 +
from score
 +
group by student_id
 +
order by sum(score) desc
 +
limit 1;
 +
</syntaxhighlight>但其实可能存在多个学生的总分一样:<syntaxhighlight lang="sql">
 +
select student_id, sum(score)
 +
from score
 +
group by student_id
 +
order by sum(score) desc;
 +
</syntaxhighlight>
 +
{| class="wikitable"
 +
|+
 +
!student_id
 +
!sum(score)
 +
|-
 +
|1
 +
|240
 +
|-
 +
|2
 +
|240
 +
|-
 +
|3
 +
|210
 +
|}
 +
所以是
 +
{| class="wikitable"
 +
|+
 +
!
 +
!
 +
!
 +
!
 +
|-
 +
|
 +
|
 +
|
 +
|
 +
|-
 +
|
 +
|
 +
|
 +
|
 +
|-
 +
|
 +
|
 +
|
 +
|
 +
|}
  
 
=== 查询单科分数最高的学生分数是多少 ===
 
=== 查询单科分数最高的学生分数是多少 ===

2024年7月7日 (日) 04:17的版本

建表

create table course (
  id integer primary key,
  name text not null
);

create table student (
  id integer primary key,
  name text not null
);

create table score (
  id integer primary key,
  course_id integer not null,
  student_id integer not null,
  score integer not null
);

准备数据

insert into course values (1, '语文'), (2, '数学'),(3,'外语');
insert into student values (1, '小张'), (2, '小王'), (3, '小马');

insert into score values (1, 1, 1, 80), (2,2,1,90), (3,3,1,70);
insert into score values (4,1,2,70),(5,2,2,90),(6,3,2,80);
insert into score values (7,1,3,80),(8,2,3,60),(9,3,3,70);

查询总分最高的学生分数是多少

先查最高分是多少

select student_id, sum(score)
from score
group by student_id
order by sum(score) desc
limit 1;

但其实可能存在多个学生的总分一样:

select student_id, sum(score)
from score
group by student_id
order by sum(score) desc;
student_id sum(score)
1 240
2 240
3 210

所以是

查询单科分数最高的学生分数是多少