How to get a row rank?

后端 未结 6 1972
一生所求
一生所求 2021-01-05 04:08

HI,

I actually posted similar (or same?) question yesterday, but I thought I need to post a new question since I have short, but clear question.

I have the f

6条回答
  •  梦谈多话
    2021-01-05 04:49

    When I needed to do something similar, I created a view that looked like this:

    CREATE VIEW rankings_view 
    AS 
    SELECT id
    ,      point
    ,      (select count(1) 
              from points b
             where  b.point > a.point) +1 as rank
    FROM points as a;
    

    This assumes that the original table was named points, obviously. Then you can get the rank of any id, or the id corresponding to any rank, by querying the view.

    EDIT

    If you want to count the number of distinct point values above each point value instead of the number of entries with point values above the current point value, you can do something like:

    CREATE VIEW rankings_view2
    AS 
    SELECT id
    ,      point
    ,      (SELECT COUNT(1) +1 AS rank 
              FROM ( SELECT DISTINCT point
                       FROM points b
                      WHERE   b.point >a.point ))
    FROM points AS a;
    

    NOTE

    Some of the other solutions presented definitely perform better than this one. They're mysql specific, so I can't really use them for what I'm doing. My application has, at most, 128 entities to rank, so this works well enough for me. If you might have tons of rows, though, you might want to look at using one of the other solutions presented here or limiting the scope of the ranking.

提交回复
热议问题