MySQL:获得每个类别的前100条记录

时间:2016-04-26 09:36:43

标签: mysql sql

我有一个名为consultant_project_score的表格,其中包含以下字段idproject_idfinal_score。我想生成一个查询,显示每个project_id的前100个final_score。我使用的是MySQL workbench 6.3,我无法使用任何create/insert语句。有没有办法实现这个目标?

3 个答案:

答案 0 :(得分:1)

未经测试,但它应该可行。技巧是为每个项目生成一个行号

select id, project_id, final_score
from 
(select id, project_id, final_score,
      @rn:= if(@project_id= project_id, @rn+ 1, 1) as rn,
      @project_id:= project_id as pi
  from t,(SELECT @rn:=0) b
  order by project_id, final_score desc) x 
where x.rn<= 100;

答案 1 :(得分:1)

这对你有用。内部查询将按project_id生成等级组,然后外部查询将过滤前100个结果。

注意:如果你有类似的project_id和score组合,它将不起作用。创造了这个小提琴,获得了2个等级。

<强> http://sqlfiddle.com/#!9/9e94d5/1

SELECT id1,
       project_id,
       final_score
FROM
  (SELECT max(t1.id) AS id1,
          t1.project_id,
          t1.final_score,
          count(*) AS rnk
   FROM consultant_project_score t1
   INNER JOIN consultant_project_score t2 ON t1.project_id=t2.project_id
   WHERE t1.final_score<=t2.final_score
   GROUP BY t1.project_id,
            t1.final_score) t
WHERE rnk<=100

答案 2 :(得分:0)

这一个没有Group BY,并使用self join的概念。这应该给你正确的输出

<强> SQL

   SELECT cps2.id, cps2.project_id,  cps2.final_score FROM 
                    (  SELECT DISTINCT project_id FROM  consultant_project_score ) cps1 
                     JOIN  consultant_project_score cps2
                                            ON cps2.id  IN ( SELECT cps3.id FROM consultant_project_score cps3 
                            WHERE cps3.project_id = cps1.projectid  
                             ORDER BY cps3.final_score  DESC LIMIT 100) 
                    ORDER BY cps2.project_id ,cps2.final_score DESC