我有如下表格,
user_id Task_name Score
__________________________________
1 101 10
1 102 9
1 103 8
2 104 10
2 105 9
3 106 9
4 107 9
4 108 8
5 109 8
5 110 7
5 111 6
6 112 10
6 113 9
6 114 8
7 115 9
7 116 8
我想获得前5名或最多5项任务。
条件:
1)至少尝试从一个用户那里获得一个任务。
输出:
User_Id Task_Name Score
____________________________________
1 101 10
2 104 10
6 112 10
3 106 9
4 107 9
答案 0 :(得分:2)
我认为这就是你所需要的:
SELECT TOP 5 User_id, Task_name, Score
FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY Score DESC) R
FROM Src
) T
ORDER BY R, Score DESC, user_id
它产生:
User_Id Task_Name Score
____________________________________
1 101 10
2 104 10
6 112 10
3 106 9
4 107 9
如果您需要排名前5位,请使用其他SELECT..ORDER
子句包装结果:
SELECT * FROM
(
SELECT TOP 5 user_id, Task_name, Score
FROM
(
SELECT *, RANK() OVER (PARTITION BY user_id ORDER BY Score DESC) R
FROM Src
) T
ORDER BY R, Score DESC, user_id
) E
ORDER BY Score DESC, user_id
答案 1 :(得分:1)
我认为这就是你想要的:
select top 5 t.*
from (select t.*,
row_number() over (partition by user_id order by score desc) as seqnum
from t
) t
where seqnum = 1
order by score desc;
row_number()
用于为每个用户选择最佳行。外部查询然后选择具有任务的前5个用户。