简体   繁体   中英

How to find rank using mysql or java(jdbc)

i have tried this mysql code to find rank/position. it works, i have realized it gives the same rank incase of a tie but after that it should skip the next rank like if three people tie in number 2, the next rank should be 5 instead of 3. i hope u understand.

SET @RANK=0,@PREV=NULL;
SELECT RANK,total FROM
(
SELECT @RANK:=IF(@PREV=COMP,@RANK,@RANK+1) AS RANK,
@PREV:=COMP AS total,ADM
FROM my_table
ORDER BY total DESC
)
AS RESULT;

who can help me here please or if anyone can help me develop a method in java that returns rank. i willl appreciate

If you want to do it in Java one way would be to get the ranks and sort them (descending or ascending depending on how your rank works). Reading the sorted array will then give you your rankings.

Edit: By "give you your ranks" I mean that you can now assign your ranks easily as you go through the array. Starting at index 0 give rank 0 (or whatever) to all elements while the value of the elements has not changed. When the value changes, increment your rank (as needed) and continue in the same fashion.

You can add another rank which is always incremented, and set the current rank to that if there is a change in the value of COMP.

SELECT Rank,total
FROM
(
    SELECT @Rank:=IF(@Prev=COMP, @Rank, @FullRank) AS Rank,
            ADM,
            @Prev:=COMP,
            COMP AS total,
            @FullRank:=@FullRank+1
    FROM my_table
    CROSS JOIN (SELECT @Rank:=0, @Prev:='fred', @FullRank:=1) Sub1
    ORDER BY total DESC
) RESULT

Note that MySQL can optimise the order of the user variables in a query which can occasionally cause issues. Having @Prev:=COMP AS total as a single line (rather than splitting it onto 2 different select items as I have done in the query above) seems to make a mess of the first rank item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM