简体   繁体   中英

Get position of an ID based on MySQL COUNT result

I am not even sure if this has been answered because I don't even know how to coin the problem. But here is what am trying to do.

I am using COUNT() to create a tabular representation of a data from top to bottom for a 30 day period.

 SELECT id FROM table WHERE col = '123' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY) AND date <=  LAST_DAY(CURRENT_DATE) GROUP BY id ORDER BY COUNT(id) DESC

And I get the result with the most at the top

id  | col
==========
id3 | 123
id5 | 123
id2 | 123
id4 | 123
id8 | 123
id5 | 123
id1 | 123
id9 | 123
id7 | 123

This works fine for a tabular view and I can use ol to create a numbering system from 1 - 10. My issue is, I want to be able to tell the position of any given id. Eg. if I want to get the position of id9 in this count result ie 8, how do I do that?

If you are using MySQL v8.0 or higher you can use the RANK function :

SELECT COUNT(*), RANK() OVER (ORDER BY COUNT(id) DESC) AS r FROM table GROUP BY id ORDER BY COUNT(id) DESC;

For previous version of mysql, you need to create the variable your self:

SELECT COUNT(*), @rank := @rank + 1 AS r FROM table, (SELECT @rank := 0) temp ORDER BY COUNT(id) DESC;

Note SELECT @rank:= 0 initiate the variable.

Updated:

To select a specific id and it's rank, you can use:

SELECT * FROM (
    SELECT id, COUNT(*), RANK() OVER (ORDER BY COUNT(id) DESC) AS r FROM table GROUP BY id ORDER BY COUNT(id) DESC
    ) ranked WHERE id = ?;

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