开发者

SQL Rank query optimization

I have the following table structure for a tab开发者_运维知识库le Player

Table Player {  
Long playerID;  
Long points;  
Long rank;  
}

Assuming that the playerID and the points have valid values, can I update the rank for all the players based on the number of points in a single query? If two people have the same number of points, they should tie for the rank.

I'm using hibernate, so cannot execute any queries with variables, so I came up with this query which is very inefficient. Can this be optimized to work with the constraints specified above?

update player g1 
    set g1.rank = 1 + 
    ((SELECT count(*) from 
    (select * from player) g2 
    where g2.points > g1.points))


If you are using MS SQL Server 2005+ T-SQL, I can recommend having a look at the fantastic ROW_NUMBER(), RANK() AND DENSE_RANK(), and NTILE() functions!

Read more here about them


There are four ranking function in SQL Server. ROW_NUMBER, RANK, DENSE_RANK, and NTILE are use to return a ranking value for each row over the partition.

For difference between them with example check the URL given below

http://www.freshcodehub.com/Article/50/implement-ranking-functions-in-sql-server

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜