Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Getting a row number (ranking) for a specific row

Tags:

mysql

I have a users table that has a column called money_sent. I want to order this table by money_sent in descending order, and then find out what "rank" a specific user has.

For example, only 111 people have spent more money than User 12392, so they would be rank 112.

How could I query this?

like image 290
Ice Avatar asked Feb 02 '09 17:02

Ice


People also ask

What is Rownum equivalent in MySQL?

MySQL doesn't support ROWNUM() function, but it since version 8.0, MySQL introduced ROW_NUMBER() function as an equivalent to return the number of the current row within its partition during data retrieval.

Does ROW_NUMBER work in MySQL?

Notice that MySQL has supported the ROW_NUMBER() since version 8.0. If you use MySQL 8.0 or later, check it out ROW_NUMBER() function. Otherwise, you can continue with the tutorial to learn how to emulate the ROW_NUMBER() function.


2 Answers

How about:

SELECT count(*) FROM users WHERE money_sent < (
    SELECT money_sent FROM users WHERE user = 'joe'
);
like image 59
Chris J Avatar answered Oct 05 '22 16:10

Chris J


SELECT Row,user, money_sent
FROM (SELECT @row := @row + 1 AS Row, user, money_sent 
       FROM table1 order by money_sent desc) 
As derived1 
like image 40
Learning Avatar answered Oct 05 '22 16:10

Learning