Here is the rows looks like:
Id Gold
1 200
2 100
3 300
4 900
5 800
6 1000
What I want to achieve is getting the rank number whose Id
equals to 5
, which is order by Gold
descending.
So after ordering, the intermediate rows should be(NOT RETURN):
Id Gold
6 1000
4 900
5 800
And the SQL should just return 3
, which is the ranking of Id = 5
row.
What is the most efficient way to achieve this?
You simply want top
, I think:
select top 3 t.*
from t
order by gold desc;
If you want the ranking of id = 5
:
select count(*)
from t
where t.gold >= (select t2.gold from t t2 where t2.id = 5);
Try This Code By using Dense_rank ():
WITH cte
AS (SELECT *,
Dense_rank()
OVER(
ORDER BY [Gold] DESC) AS rank
FROM your_table)
SELECT rank
FROM cte
WHERE id = 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.