我有10名学生的记录。
id markss
1 50
2 60
3 40
4 78
5 45
6 55
7 35
8 86
9 56
10 83
现在我要展示位置,即学生的第一,第二和第三位置。 任何人都可以帮我在SQL Server中找到它。
答案 0 :(得分:3)
SELECT id, markss, DENSE_RANK() OVER(ORDER BY markss DESC) AS position
FROM myTable
ORDER BY markss DESC
例如
CREATE TABLE #Mytable (id int,markss INT)
INSERT #Mytable VALUES(1, 50)
INSERT #Mytable VALUES(2, 60)
INSERT #Mytable VALUES(3, 40)
INSERT #Mytable VALUES(4, 78)
INSERT #Mytable VALUES(5, 45)
INSERT #Mytable VALUES(6, 55)
INSERT #Mytable VALUES(7, 35)
INSERT #Mytable VALUES(8, 86)
INSERT #Mytable VALUES(9, 56)
INSERT #Mytable VALUES(10, 83)
现在添加重复分数
INSERT #Mytable VALUES(11, 86)
使用3个排名函数进行查询
SELECT id, markss,
DENSE_RANK() OVER(ORDER BY markss DESC) AS DensePosition,
RANK() OVER(ORDER BY markss DESC) AS RankPOSITION,
ROW_NUMBER() OVER(ORDER BY markss DESC) AS RowPosition
FROM #Mytable
ORDER BY markss DESC
<强>输出强>
8 86 1 1 1
11 86 1 1 2
10 83 2 3 3
4 78 3 4 4
2 60 4 5 5
9 56 5 6 6
6 55 6 7 7
1 50 7 8 8
5 45 8 9 9
3 40 9 10 10
7 35 10 11 11
答案 1 :(得分:0)
对于SQL Server 2005 +:
select id, markss, row_number() over (order by markss desc) as Position
from YourTable
order by Position