选择具有三个最大值的组

时间:2016-03-03 12:57:45

标签: mysql sql select group-by limit

考虑这些数据:

---+-----------+-------+--+
| id |   name    | grade |  |
+----+-----------+-------+--+
| 13 | Maria     |    10 |  |
| 18 | Lorenzo   |    10 |  |
|  2 | Cissa     |    10 |  |
|  3 | Neto      |     9 |  |
| 15 | Gabriel   |     9 |  |
| 10 | Laura     |     9 |  |
| 12 | Joãozinho |     8 |  |
| 16 | Sergio    |     8 |  |
|  8 | Adriele   |     8 |  |
|  6 | Jorgito   |     8 |  |
|  5 | Aline     |     8 |  |
|  1 | Cintia    |     8 |  |
| 19 | Fabiana   |     7 |  |
| 11 | Vinicius  |     7 |  |
|  9 | Tatiane   |     7 |  |
|  7 | Chico     |     7 |  |
|  4 | Marcos    |     7 |  |
| 14 | Pedro     |     6 |  |
| 17 | Mauricio  |     6 |  |
| 20 | Leonardo  |     6 |  |
+----+-----------+-------+--+

我需要三个年级的学生。我想我需要按等级对数据进行分组,并限制前三组。

“SELECT * FROM student GROUP BY grade LIMIT 3”只给了我3行,这不是我想要的。

我曾尝试使用HAVING过滤群组,但没有成功。我不想设置滤波器等级> MAX(等级)-2,因为理论上我不会知道等级。但是这个过滤器无论如何都没有用。

我正在使用MySQL。请帮忙!

3 个答案:

答案 0 :(得分:2)

您可以使用fr

执行此操作
join

在大多数数据库中,您可以使用select s.* from student s join (select grade from student group by grade order by grade desc limit 3 ) g3 on s.grade = g3.grade; 执行此操作:

in

然而,MySQL似乎拒绝这种语法。

答案 1 :(得分:0)

select s1.*
from students s1
  join (select distinct grade from students 
        order by grade desc limit 3) s2 on s1.grade = s2.grade

可替换地:

select *
from students 
where grade >= (select distinct grade from students 
                order by grade desc limit 2,1)

答案 2 :(得分:0)

选择s。* 来自学生的加入      (选择前三名       来自学生       按年级分组       按等级desc排序      )g3      在s.grade = g3.grade;