相关/类似问题:MySQL - Get row number on select,Select only partial result but get total number of rows
我目前有这张桌子:
+----+--------------------+---------------+--------+
| id | accountId | competitionId | rating |
+----+--------------------+---------------+--------+
| 1 | theidoftheaccount1 | 1 | 100 |
| 2 | theidoftheaccount2 | 3 | 90 |
| 3 | theidoftheaccount3 | 1 | 80 |
| 4 | theidoftheaccount4 | 1 | 50 |
+----+--------------------+---------------+--------+
我想用accountId='theidoftheaccount3'
获取行,所以我调用通常的SQL语句SELECT * FROM competitors WHERE competitionId='someotherid1' AND accountId='theidoftheaccount3 ' ORDER BY rating DESC
,一切都很好。
问题:现在,我想知道我所得到的行的行号,但只知道所有其他具有competitionId='someotherid1'
的行。该行号将是同一竞争中所有其他竞争对手中竞争对手的“排名”。
所以基本上在一天结束时我会回来:
+----+--------------------+---------------+--------+-----------+
| id | accountId | competitionId | rating | rowNumber |
+----+--------------------+---------------+--------+-----------+
| 3 | theidoftheaccount3 | 1 | 80 | 2 |
+----+--------------------+---------------+--------+-----------+
如何完成?
一种方法是在子查询中使用row_number()
:
select c.*
from (select c.*,
rank() over (partition by competitionid order by rating desc) as ranking
from competitors c
where competitionId = 'someotherid1'
) c
where accountId = 'theidoftheaccount3';