MySQL 基于 GROUP BY SELECT n 条记录
假设我有 SQL 记录:
Country | Number USA | 300 USA | 450 USA | 500 USA | 100 UK | 300 UK | 400 UK | 1000
我正在做这样的事情:SELECT * FROM table GROUP BY Country
。
如果我想选择只显示每个国家中 2 个最大数字的结果怎么办?我怎样才能存档这个?
结果将是:
Country | Number USA | 450 USA | 500 UK | 400 UK | 1000
Lets say I have SQL records:
Country | Number USA | 300 USA | 450 USA | 500 USA | 100 UK | 300 UK | 400 UK | 1000
And I am doing something like this: SELECT * FROM table GROUP BY Country
.
What if, I want to choose to display the result with 2 greatest number only in each country? How can I archive this?
The result would be:
Country | Number USA | 450 USA | 500 UK | 400 UK | 1000
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
示例数据
第一个选项是使用像 Scrum Meister 所示的变量的伪排名,但在这里作为单个语句呈现
如果您在前端使用它,并且只需要 2 个计数,那么您可以使用此形式返回列表中的计数(单列)
结果是
如果有可能出现平局,则第二种形式的这种变体将删除平局并显示“每个国家/地区前 2 个不同的数字”作为记录。
结果
Sample data
The first option is a pseudo rank using variables like The Scrum Meister has shown, but presented here as a single statement
If you are using this in a front end, and only need 2 counts, then you can use this form that returns the counts in a list (single column)
The result is
If it is possible for ties to occur, then this variation of the 2nd form removes the ties and shows the "top 2 distinct numbers per country", as records.
Result
由于MySql没有内置的RANK函数,查询可能会很慢:
Since MySql does not have a built in RANK function, the query may be slow:
让我们将您的表命名为 TName,然后他们的查询将是。
Lets name your table TName, then they query would be.