SQL 查询 - 查找用户在测验中的排名
SQL Query - Finding the Rank of a User in a Quiz
我的数据库中有一个 QuizAttempt table,如下所示
| QAID | QID | UID | Score | Time |
| ---- | --- | --- | ----- | ---- |
| 1 | 5 | 3 | 119 | 105 |
| 2 | 5 | 3 | 117 | 70 |
| 3 | 5 | 3 | 119 | 90 |
| 4 | 5 | 4 | 120 | 130 |
其中 QAID
= 测验尝试 ID,QID
= 测验 ID,UID
= 用户 ID,Score
= 该次尝试的分数,Time
= 以秒为单位的时间
我想根据分数先降序获取用户排名,如果分数相同,则按时间升序获取用户排名。此外,我还必须将多次参加测验的用户分组,并展示他们的最佳尝试。
所以结果应该是这样的(Grouped UID 3)
| QAID | QID | UID | Score | Time |
| ---- | --- | --- | ----- | ---- |
| 4 | 5 | 4 | 120 | 130 |
| 3 | 5 | 3 | 119 | 90 |
我知道我可以应用 Group By UID,然后 Max(Score) 但另外我还必须根据该记录选择时间,但是我是否在 GROUP BY 中选择 119 旁边的最小分数?
因为如果我写
Select QID, UID, Max(Score) as Topper, Min(Time) as MinTime from QuizAttempt
Group By QID, UID
Order By Topper DESC
我明白了
| QID | UID | Topper | MinTime |
| --- | --- | ------ | ------- |
| 5 | 4 | 120 | 130 |
| 5 | 3 | 119 | 70 |
我得到 70,这是总的 Min(Time) 并且属于 Score 117
的记录
如果我试试这个
Select QID, UID, Max(Score) as Topper, Min(Time) as MinTime from QuizAttempt
Group By QID, UID,Score
Order By Topper DESC
我明白了
| QID | UID | Topper | MinTime |
| --- | --- | ------ | ------- |
| 5 | 4 | 120 | 130 |
| 5 | 3 | 119 | 90 |
| 5 | 3 | 117 | 70 |
如何正确分组?我正在使用 MS SQL Management Studio 2008
您可以使用 row_number()
:
select qa.*
from (select qa.*,
row_number() over (partition by uid order by score desc, time asc) as seqnum
from QuizAttempt qa
) qa
where seqnum = 1;
我的数据库中有一个 QuizAttempt table,如下所示
| QAID | QID | UID | Score | Time |
| ---- | --- | --- | ----- | ---- |
| 1 | 5 | 3 | 119 | 105 |
| 2 | 5 | 3 | 117 | 70 |
| 3 | 5 | 3 | 119 | 90 |
| 4 | 5 | 4 | 120 | 130 |
其中 QAID
= 测验尝试 ID,QID
= 测验 ID,UID
= 用户 ID,Score
= 该次尝试的分数,Time
= 以秒为单位的时间
我想根据分数先降序获取用户排名,如果分数相同,则按时间升序获取用户排名。此外,我还必须将多次参加测验的用户分组,并展示他们的最佳尝试。
所以结果应该是这样的(Grouped UID 3)
| QAID | QID | UID | Score | Time |
| ---- | --- | --- | ----- | ---- |
| 4 | 5 | 4 | 120 | 130 |
| 3 | 5 | 3 | 119 | 90 |
我知道我可以应用 Group By UID,然后 Max(Score) 但另外我还必须根据该记录选择时间,但是我是否在 GROUP BY 中选择 119 旁边的最小分数?
因为如果我写
Select QID, UID, Max(Score) as Topper, Min(Time) as MinTime from QuizAttempt
Group By QID, UID
Order By Topper DESC
我明白了
| QID | UID | Topper | MinTime |
| --- | --- | ------ | ------- |
| 5 | 4 | 120 | 130 |
| 5 | 3 | 119 | 70 |
我得到 70,这是总的 Min(Time) 并且属于 Score 117
的记录如果我试试这个
Select QID, UID, Max(Score) as Topper, Min(Time) as MinTime from QuizAttempt
Group By QID, UID,Score
Order By Topper DESC
我明白了
| QID | UID | Topper | MinTime |
| --- | --- | ------ | ------- |
| 5 | 4 | 120 | 130 |
| 5 | 3 | 119 | 90 |
| 5 | 3 | 117 | 70 |
如何正确分组?我正在使用 MS SQL Management Studio 2008
您可以使用 row_number()
:
select qa.*
from (select qa.*,
row_number() over (partition by uid order by score desc, time asc) as seqnum
from QuizAttempt qa
) qa
where seqnum = 1;