Postgres选择(按类型分组)

时间:2016-01-16 08:17:15

标签: sql postgresql select group-by greatest-n-per-group

我的表格如下:

ID     NAME      TYPE  RATING
1      name1      1      98
2      name2      1      17
3      name3      2      77
4      name4      2      53
5      name5      2      23
6      name6      4      64
7      name7      3      78
8      name8      3      56
9      name9      3      22
10     name10     4      56
11     name11     4      99
.      ...        .      ..

我如何从这个表中进行选择,例如,每个'类型'中只有(2,3 ...等,N)行。评分最高?

结果示例(2行):

ID     NAME      TYPE  RATING
1      name1      1      98
2      name2      1      17
3      name3      2      77
4      name4      2      53
7      name7      3      78
8      name8      3      56
6      name6      4      64
11     name11     4      99
.      ...        .      ..

1 个答案:

答案 0 :(得分:3)

您可以使用row_number窗口函数为每个类型分配排名:

SELECT id, name, type, rating
FROM   (SELECT id, name, type, rating,
               ROW_NUMBER() OVER (PARTITION BY type ORDER BY rating DESC) AS rn
        FROM   myable)
WHERE  rn <= 3; -- Or any other number of rows per type you wish