简体   繁体   中英

In SQL, I need to generate a ranking (1st, 2nd, 3rd) column, getting stuck on “ties”

I have a query that calculates points based on multiple criteria, and then orders the result set based on those points.

SELECT * FROM (
    SELECT
         dbo.afunctionthatcalculates(Something, Something) AS Points1
        ,dbo.anotherone(Something, Something) AS Points2
        ,dbo.anotherone(Something, Something) AS Points3
        ,[TotalPoints] = dbo.function(something) + dbo.function(something) 
) AS MyData
ORDER BY MyData.TotalPoints 

So my first stab at adding placement, rankings.. was this:

SELECT ROW_NUMBER() OVER(MyData.TotalPoints) AS Ranking, * FROM (
    SELECT same as above
) AS MyData
ORDER BY MyData.TotalPoints

This adds the Rankings column, but doesn't work when the points are tied.

Rank  |  TotalPoints
--------------------
1        100
2        90
3        90
4        80

Should be:

Rank  |  TotalPoints
--------------------
1        100
2         90
2         90
3         80

Not really sure about how to resolve this.

Thank you for your help.

您应该使用DENSE_RANK()函数,该函数考虑了联系,如此处所述: http : //msdn.microsoft.com/zh-cn/library/ms173825.aspx

DENSE_RANK()而不是ROW_NUMBER()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM