MySQL:如何通过 GROUP BY 字段来检索 ORDER BY 另一个字段的行?
假设以下数据:
数据:
id | date | name | grade
--------+---------------+-----------+---------------
1 | 2010/12/03 | Mike | 12
2 | 2010/12/04 | Jenny | 12
3 | 2010/12/04 | Ronald | 15
4 | 2010/12/03 | Yeni | 11
我想知道每天谁的成绩最好,如下所示:
期望结果:
id | date | name | grade
--------+---------------+-----------+---------------
1 | 2010/12/03 | Mike | 12
3 | 2010/12/04 | Ronald | 15
我认为查询应该如下所示:
SELECT name FROM mytable
GROUP BY date
ORDER BY grade DESC
但它返回类似这样的内容:
当前不需要的结果:
id | date | name | grade
--------+---------------+-----------+---------------
1 | 2010/12/03 | Mike | 12
2 | 2010/12/04 | Jenny | 12
我搜索并找到了原因:
GROUP BY发生在ORDER BY之前,因此它看不到也无法应用ORDER。
所以我如何在 GROUP BY 上应用 ORDER?
注意:请记住,我需要最简单的查询,因为我的查询实际上非常复杂,我知道我可以通过一些子查询或联接来实现这个结果,但我想知道如何应用按顺序分组。谢谢
assume following data:
Data:
id | date | name | grade
--------+---------------+-----------+---------------
1 | 2010/12/03 | Mike | 12
2 | 2010/12/04 | Jenny | 12
3 | 2010/12/04 | Ronald | 15
4 | 2010/12/03 | Yeni | 11
i want to know who has the best grade in each day, something like this:
Desired Result:
id | date | name | grade
--------+---------------+-----------+---------------
1 | 2010/12/03 | Mike | 12
3 | 2010/12/04 | Ronald | 15
i thought query should look like this:
SELECT name FROM mytable
GROUP BY date
ORDER BY grade DESC
but it returns something like this:
Current Unwanted Result:
id | date | name | grade
--------+---------------+-----------+---------------
1 | 2010/12/03 | Mike | 12
2 | 2010/12/04 | Jenny | 12
i searched and i found the reason:
GROUP BY happens before ORDER BY so it does not see and can't apply ORDER.
so how can i apply ORDER on GROUP BY?
Note: please keep in mind that i need the most simple query, because my query is actually very complex, i know i can achieve this result by some subquery or JOINing, but i want to know how to apply ORDER to GROUP BY. thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在这个例子中使用了 Oracle,但是 SQL 应该在 mysql 中工作(您可能需要调整 to_date 的内容才能与 mysql 一起工作)。您确实需要一个子查询来完成您所要求的操作。
结果:
I used Oracle for this example, but the SQL should work in mysql (you may need to tweak the to_date stuff to work with mysql). You really need a subquery here to do what you are asking.
Results:
我知道您说过您想要一个仅 GROUP / ORDER 的解决方案,但在这种情况下您需要使用子查询。最简单的方法是这样的:
这会显示多个学生是否分享了当天的最高成绩。
I know you said you wanted a GROUP / ORDER only solution but you will need to use a subquery in this instance. The simplest way would be something like this:
This would show multiple students if they shared the highest grade for the day.