MS访问 - 以递增方式排列相等的值

时间:2016-01-28 15:25:08

标签: sql ms-access rank

是否可以对Access中的记录进行排名,其中重复值被赋予增量排名(如SQL Server中的row_number函数)?

我想对以下记录进行排名:

ID     Type    Score
1      Team1   4
1      Team2   2
1      Team3   1
1      Team4   1

我目前的查询:

select *
from tbl as tbl1 
where tbl1.ID in 
(  select top 3 Type
   from tbl as tbl2
   where tbl2.ID = tbl1.ID
   order by tbl2.Score )

将它们排列如下

ID     Type    Score    Rank
1      Team1   4        1
1      Team2   2        2
1      Team3   1        3
1      Teams   1        3

我需要对它们进行排名:

ID    Type     Score    Rank
1      Team1   4        1
1      Team2   2        2
1      Team3   1        3
1      Team4   1        4

可以在Access中完成吗?

修改 排名也需要分组

更大的数据样本以及我想在派生列中表示的内容,有些ID比其他ID有更多记录:

ID    Type     Score    Rank
1     Team1    4        1
1     Team2    2        2
1     Team3    1        3
1     Team4    1        4
2     Team1    2        1
2     Team3    2        2
2     Team2    1        3
4     Team1    4        1
4     Team3    4        2
4     Team5    3        3
4     Team4    1        4
4     Team2    1        5

最终我想为每个ID选择前3行

1 个答案:

答案 0 :(得分:2)

在两个条件聚合计数子查询上使用差分方程考虑此解决方案。 Tiebreaker使用字母顺序Type的顺序:

SELECT tbl.ID, tbl.Type, tbl.Score,
   (SELECT Count(*) FROM tbl sub WHERE sub.ID = tbl.ID
    AND sub.Score >= tbl.Score ) 
    -
   (SELECT Count(*) - 1 FROM tbl sub WHERE sub.ID = tbl.ID
    AND sub.Type >= tbl.Type
    AND sub.Score = tbl.Score) As [Rank]

FROM tbl
ORDER BY ID, Score DESC, Type;