MySQL find top results for each group

时间秒杀一切 提交于 2019-12-20 05:58:46

问题


I have searched a lot, but I can't find an answer or something near.

I have a table like this:

id              int(11) NO  PRI     auto_increment
attribute_id    int(11) YES         
user_id         int(11) YES         
result          int(11) YES             
x10             int(11) YES 

I need about 5 results from each attribute_id.

attribute_id can be any number, so at first, I need to check for the attribute_id, and next I have to check for the results for each attribute_id.

I can't find out how I do this without any programming language other than MySQL, but I know you can.

Example:

attribute_id    result
1               200
1               149
1               123
2               322
2               321
2               300
3               ...
3               ...

And so on.


回答1:


SELECT  attribute_id, result
FROM    TableName a
WHERE 
        (
            SELECT  COUNT(*) 
            FROM    TableName b
            WHERE   a.attribute_id = b.attribute_id 
                    AND a.result <= b.result
        ) <= 5
  • SQLFiddle Demo



回答2:


     SELECT     attribute_id, result
     FROM   TableName a
      WHERE 
    (
        SELECT  COUNT(*) 
        FROM    TableName b
        WHERE   a.attribute_id = b.attribute_id 
                AND a.result <= b.result
    ) <= 5 order by result DESC;


来源:https://stackoverflow.com/questions/16277000/mysql-find-top-results-for-each-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!