Max SQL的分钟

时间:2017-05-11 19:05:29

标签: mysql sql join group-by

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 个答案:

答案 0 :(得分:1)

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

为每学期订购的测试构建行号,并保留编号为#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没有这个功能。)

答案 1 :(得分:0)

select a.name as semester
     , b.name as subject
     , min(c.score) as lowestscore
from subjects as b
   join semesters as a on a.id = b.semester_id
   join tests as c on c.subject_id = b.id
group by a.name, b.name

你可能想订购或者什么,但这应该给你你想要的东西。您可以为学期或科目的范围添加更多的鉴别符,但这将产生学期的名称,科目的名称以及该学期/科目的最低分数。