从每组mysql获得前3名最高记录

时间:2018-01-11 12:38:43

标签: mysql

我有一个桌上学生。我需要每组最高的3个最高记录。该查询应适用于动态添加的组。无需在查询中设置组的默认值。

学生表:

id    name    mark       subject
--------------------------------------
1     kannan     60         French
2     balan      77         French
3     raja       88         French
4     sheik      78         French
5     satheesh   98         French
6     Ravi       90         French
7     Vishnu     90         English
8     siva       100        English
9     suresh     50         English
10    ramesh     59         English
11    ganesh     97         English
12    david      58         English

预期结果:

name      mark    subject
---------------------------
Ravi      90      French
Satheesh  98      French
raja      88      French
siva      100     English
ganesh    97      English
ramesh    59      English

我试过查询:

SELECT name, mark, subject from (SELECT name, mark, subject order by mark 
desc LIMIT 3) as ss group by subject, mark;

但我没有得到正确的值。

1 个答案:

答案 0 :(得分:0)

(SELECT NAME ,mark, SUBJECT FROM `student ` WHERE SUBJECT = 'French' ORDER BY  mark DESC LIMIT 3)
UNION 
(SELECT NAME ,mark, SUBJECT FROM `student ` WHERE SUBJECT = 'English' ORDER BY  mark DESC LIMIT 3)