MYSQL获取另一列指定的组的列中的最小值

时间:2017-03-14 21:51:07

标签: mysql sql greatest-n-per-group

我有一个看起来像这样的表:

id  name  yearofstudy  mark

1   Alain A       2    75
2   Michael B     3    85
3   Chen C        1    55
4   Caroline D    2    60
5   Mohamed E     2    60
6   Alex F        1    55
7   Sofia O       3    78
8   Samir O       1    85
9   Rob G         2    78
10   Big K        3    55

我试图获得每年最低(和最高)分数的学生的身份,姓名,年份和分数,这将给予:

id  name  yearofstudy  mark

3  Chen C       1      55
4  Caroline D   2      60
10  Big K       3      55

SQL并不是我的强项,而且我一直在尝试使用MIN()函数,但我还没有设法把它弄好,并且非常感谢一些帮助。

2 个答案:

答案 0 :(得分:2)

使用子查询获取每个min()的{​​{1}}和max(),并将其加入原始表格。 (你说你想要最低和最高,对吗?)

yearofstudy

或每年最低select t.id, t.name, t.yearofstudy, t.mark from t inner join ( select yearofstudy , min(mark) as minMark , max(mar) as maxMark from t group by yearofstudy ) as m on t.yearofstudy = m.yearofstudy and (t.mark = minMark or t.mark = maxMark)

mark

答案 1 :(得分:0)

您可以按如下方式编写查询:

SELECT t1.* from your_table t1
INNER JOIN (
    SELECT yearofstudy, MIN(marks) as marks 
        FROM your_table GROUP BY yearofstudy
    ) t2
    ON t1.yearofstudy = t2.yearofstudy
    AND t1.marks = t2.marks
GROUP BY t1.yearofstudy
ORDER BY t1.yearofstudy, t1.id;

如果需要MIN的所有yearofstudy条记录,那么您只需删除GROUP BY t1.yearofstudy

Demo