在SQL中,我需要生成一个排名(第1,第2,第3)列,陷入“关系”

时间:2014-05-19 14:54:54

标签: sql sql-server sql-server-2008 sql-server-2012

我有一个基于多个条件计算点数的查询,然后根据这些点对结果集进行排序。

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 

所以我第一次尝试添加位置,排名......就是这样:

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

这会添加排名列,但在点数相关时不起作用。

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

应该是:

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

不确定如何解决此问题。

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

您应该使用考虑关系的DENSE_RANK()函数,如下所述:http://msdn.microsoft.com/en-us/library/ms173825.aspx

答案 1 :(得分:1)

DENSE_RANK()而不是ROW_NUMBER()