如何获取每个类别的前n条记录

时间:2013-05-24 10:21:22

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

我有一张如下表格,位于SQL FIDDLE

id  empid proj  file  rating
~~  ~~~~~ ~~~~  ~~~~  ~~~~~~
1   1863   G1   file1    1
2   P4645  G1   file2    1
3   P6682  G1   file3    1
4   P6682  G1   file4    1
5   P4645  G1   file5    1
6   P4645  G1   file6    1
7   1863   G1   file7    1
8   1863   G1   file8    1
9   1863   G1   file19   1
10  P6682  G2   file21   1
11  1863   G2   file55   1
12  P6682  G2   file60   1
13  P4645  G2   file85   1
14  P6682  G2   file91   1
15  P4645  G2   file93   1
16  P4645  G3   file95   1
17  P4645  G3   file100  1
18  P4645  G3   file125  1
19  1863   G3   file131  1
20  1863   G3   file150  1
21  P6682  G3   file193  1
21  P6682  G3   file193  1

我需要一个SQL来从上表中为每个类别(proj)检索前n个(比如前2个)评分计数

所需的OP如下

proj  empid  ratings
~~~~  ~~~~~  ~~~~~~~
 G1   1863      4
 G1   P4645     3
 G2   P6682     3
 G2   P4645     2
 G3   P4645     3
 G3   1863      2
 G3   P6682     2

试图跟随thread中的meathod,但无法从我所拥有的表格中获得。

2 个答案:

答案 0 :(得分:2)

尝试此查询

select * from 
(select @rn:=if(@prv=Proj, @rn+1, 1) as rId,
@prv:=Proj,
empid, 
stars
from
(SELECT
          starRatings.Proj
        , starRatings.empid
        , count(*) as stars
    FROM achivement as starRatings
    group by starRatings.Proj,starRatings.empid
order by proj, stars desc)a
join 
(select @rn:=0, @prv:='') tmp
)tmp where rid <= 2

SQL FIDDLE

select * from 
(select @rn:=if(@prv=Proj, if(@prvv=stars, @rn, @rn+1), 1) as rId,
@prv:=Proj,
empid, 
@prvv:=stars
from
(SELECT
          starRatings.Proj
        , starRatings.empid
        , count(*) as stars
    FROM achivement as starRatings
    group by starRatings.Proj,starRatings.empid
    order by proj, stars desc)t
join 
(select @rn:=0, @prv:='', @prvv:=0) tmp
)tmp where rid <= 2

SQL FIDDLE

| RID | @PRV:=PROJ | EMPID | @PRVV:=STARS |
-------------------------------------------
|   1 |         G1 |  1863 |            4 |
|   2 |         G1 | P4645 |            3 |
|   1 |         G2 | P6682 |            3 |
|   2 |         G2 | P4645 |            2 |
|   1 |         G3 | P4645 |            3 |
|   2 |         G3 |  1863 |            2 |
|   2 |         G3 | P6682 |            2 |

答案 1 :(得分:1)

使用: -

(
  select proj,empid,rating,count(rating)
  from achivement 
  where `proj` =  'G1'
  group by empid
  order by count(rating) desc
  LIMIT 2
)
UNION ALL
(
  select proj,empid,rating,count(rating)
  from achivement 
  where `proj` =  'G2'
  group by empid
  order by count(rating) desc
  LIMIT 2
)
UNION ALL
    (
      select proj,empid,rating,count(rating)
      from achivement 
      where `proj` =  'G3'
      group by empid
      order by count(rating) desc
      LIMIT 2
    )

SQL FIDDLE

截图 enter image description here