Solved Rank sequentially without skipping any number (1 Viewer)

Tajaldeen

New member
Local time
Today, 16:14
Joined
Jan 24, 2023
Messages
4
Hi Guys,
I have a table with three fields: ID, Name, Mark
i also have created the following Query which ranks students in the table based on Mark
Code:
SELECT T2.Name, 1+(SELECT COUNT(T1.Mark)
FROM
[Table] AS T1
WHERE T1.Mark >T2.Mark) AS Rank
FROM [Table] AS T2
ORDER BY T2.Mark DESC;

the problem: if there is a duplicated mark in tow records the query will skip a number like this:
John 50 1
Mark 60 2
Ali 60 2
Pall 70 4
i dont want number 3 to be skipped so the rank will be like this: 1,2,2,3
is there any solution ?
 

ebs17

Well-known member
Local time
Today, 15:14
Joined
Feb 7, 2020
Messages
1,946
is there any solution ?
Where there is a will, there's a way.
SQL:
SELECT
   T2.Name,
   1 +
   (
      SELECT
         COUNT(*)
      FROM
         (
            SELECT DISTINCT
               Mark
            FROM [TABLE]
               ) AS T1
      WHERE
         T1.Mark > T2.Mark) AS Rank
FROM
   [Table] AS T2
ORDER BY
   T2.Mark DESC
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 21:14
Joined
May 7, 2009
Messages
19,245
You add Autonumber (say, ID) to your Table then create this Function:
Code:
Public Function fnRank(ByVal Table As String, FieldToRank As String, ByVal AutoFieldName As String, ByVal AutoFieldValue As Long)
    Dim i As Long
    With CurrentDb.OpenRecordset( _
        "select * From [" & Table & "] Order By [" & FieldToRank & "] Desc;", dbOpenSnapshot, dbReadOnly)
        .FindFirst "[" & AutoFieldName & "] = " & AutoFieldValue
        fnRank = .AbsolutePosition + 1
    End With
End Function

your query will look like this:

Code:
SELECT
    yourTable.Name,
    yourTable.Mark,
    fnRank("yourTable","Mark","ID",[ID]) AS Ranking
FROM yourTable
ORDER BY yourTale.Mark DESC;
 

Tajaldeen

New member
Local time
Today, 16:14
Joined
Jan 24, 2023
Messages
4
Where there is a will, there's a way.
SQL:
SELECT
   T2.Name,
   1 +
   (
      SELECT
         COUNT(*)
      FROM
         (
            SELECT DISTINCT
               Mark
            FROM [TABLE]
               ) AS T1
      WHERE
         T1.Mark > T2.Mark) AS Rank
FROM
   [Table] AS T2
ORDER BY
   T2.Mark DESC
Amazing .... thank you very very very much, you just solved a big problem.
where there is a will , there is a way.
 

Users who are viewing this thread

Top Bottom