gpt4 book ai didi

mysql - Max SQL 的分钟数

转载 作者:行者123 更新时间:2023-11-28 23:15:52 24 4
gpt4 key购买 nike

Semesters Table
+----+------+
| ID | Name |
+----+------+
| 1 | 1st |
| 2 | 2nd |
+----+------+

Subjects Table
+----+-------------+-------------+
| ID | Semester Id | Name |
+----+-------------+-------------+
| 1 | 1 | Mathematics |
| 2 | 1 | English |
| 3 | 2 | Mathematics |
| 4 | 2 | English |
+----+-------------+-------------+

Tests Table
+----+------------+-------+
| ID | Subject ID | Score |
+----+------------+-------+
| 1 | 1 | 70 |
| 2 | 1 | 75 |
| 3 | 2 | 75 |
| 4 | 2 | 70 |
| 5 | 3 | 75 |
| 6 | 3 | 70 |
| 7 | 4 | 70 |
| 8 | 4 | 75 |
+----+------------+-------+

我可以通过在测试 ID 上使用 MAX 获得第二次测试的分数,然后按主题 ID 对它们进行分组。但是,然后我必须获得按学期分组的分数的最小值。

是否有可能在单个 SQL 语句中获得每学期最低分数的 2ND 测试?

结果集看起来像这样。

+----------+-------------+-------+
| Semester | Subject | Score |
+----------+-------------+-------+
| 1st | English | 70 |
| 2nd | Mathematics | 70 |
+----------+-------------+-------+

这是在 MySQL 中。

最佳答案

您正在寻找每学期第二低的测试。

为每学期的有序测试建立行号,并与编号为 #2 的行保持一致。一种方法是使用相关子查询。另一个是变量。

select 
sem.name as semester,
sub.name as subject,
tst.score
from semesters sem
join subjects sub on sub.semester_id = sem.id
join tests tst on tst.subject_id = sub.id
where
(
select count(*)
from subjects sub2
join tests tst2 on tst2.subject_id = sub2.id
where sub2.semester_id = sub.semester_id
and sub2.id <= sub.id
and tst2.score <= tst.score
) = 2
order by sub.semester_id;

如果出现平局,则选择其中一行,如您的示例所示。

使用变量可能比上述查询更快。通过查找如何在 MySQL 中模拟 ROW_NUMBER,您将很容易找到该方法。 (其他DBMS使用ROW_NUMBER就简单多了,但是MySQL没有这个功能。)

关于mysql - Max SQL 的分钟数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43923718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com