我想根据他获得的分数计算每个学生的等级。但是,如果标记处于-ve值,则查询不会显示相应的答案。
SELECT a1.ResultByTestId, a1.ObtainedMarks, COUNT(a2.ObtainedMarks) Rank
FROM ResultByTest a1, ResultByTest a2
WHERE a1.ObtainedMarks < a2.ObtainedMarks
or
(a1.ObtainedMarks=a2.ObtainedMarks and a1.StudentId = a2.StudentId)
GROUP BY a1.ObtainedMarks, a1.ResultByTestId
ORDER BY a1.ObtainedMarks DESC, Rank DESC
,答案表是: -
resutlByTestId ObtainedMarks Rank
11 36 1
10 22 2
3 9 3
9 7 4
6 5 5
8 3 6
7 2 7
4 0 8
5 0 8
1 0 8
2 0 8
13 -5 12
有人帮助我吗?
答案 0 :(得分:2)
您可以使用Dense_Rank功能
执行此操作Select
StudentID,
ObtainedMarks,
Dense_Rank() Over (Order By ObtainedMarks Desc) as Rank
From
ResultByTest
http://sqlfiddle.com/#!3/a9e5c/1
你通常使用等级的原因是,当你问得到-5的人你来的时候他们会说“第9”。然后你问,有多少人打你“12”。然后你看起来很困惑。
答案 1 :(得分:1)
您应该在MSSQL 2008中使用DENSE_RANK() function:
SELECT ResultByTestId, ObtainedMarks,
DENSE_RANK() OVER (order by ObtainedMarks desc) as Rank
FROM ResultByTest
ORDER by ObtainedMarks DESC;
这里也是COUNT(DISTINCT <>)
的查询:
SELECT a1.ResultByTestId, a1.ObtainedMarks,
COUNT(DISTINCT a2.ObtainedMarks) Rank
FROM ResultByTest a1, ResultByTest a2
WHERE a1.ObtainedMarks < a2.ObtainedMarks
or
(a1.ObtainedMarks=a2.ObtainedMarks and a1.StudentId = a2.StudentId)
GROUP BY a1.ObtainedMarks, a1.ResultByTestId
ORDER BY a1.ObtainedMarks DESC, Rank DESC
答案 2 :(得分:0)
输出是正确的,因为-ve得分没有问题,因为四名学生得到0并排名第8 所以 8-8 8-9 8-10 8-11
这是如何计算所以下一个等级显然是12
答案 3 :(得分:0)
--setup test data
DECLARE @ResultByTest TABLE (ResultByTestId int, ObtainedMarks int)
INSERT INTO @ResultByTest VALUES
(11, 36),
(10, 22),
(3, 9),
(9, 7),
(6, 5),
(8, 3),
(7, 2),
(4, 0),
(5, 0),
(1, 0),
(2, 0),
(13, -5)
-- this will give you the results you have
select *, RANK() OVER (ORDER BY ObtainedMarks DESC) AS [Rank]
from @ResultByTest
-- this will give you the results I think you want
select *, DENSE_RANK() OVER (ORDER BY ObtainedMarks DESC) AS [Rank]
from @ResultByTest
答案 4 :(得分:0)
使用DENSE_RANK消除差距。
DECLARE @ObtainedMarks TABLE (
ResultByTestId INT,
ObtainedMarks INT,
StudentId INT
)
INSERT INTO @ObtainedMarks VALUES
(1,0,1),
(2,0,1),
(3,9,1),
(4,0,1),
(5,0,1),
(6,5,1),
(7,2,1),
(8,3,1),
(9,7,1),
(10,22,1),
(11,36,1),
(13,-5,1)
SELECT
ResultByTestId,
ObtainedMarks,
DENSE_RANK() OVER (order by ObtainedMarks desc) [Rank]
FROM @ObtainedMarks