我的表格如下:
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
. ... . ..
答案 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