Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get position of an ID based on MySQL COUNT result

Tags:

php

mysql

count

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 i.e. 8, how do I do that?

like image 610
Jay Smoke Avatar asked Mar 14 '21 17:03

Jay Smoke


1 Answers

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 = ?;

like image 153
Amir MB Avatar answered Nov 07 '22 21:11

Amir MB