简体   繁体   English

根据 MySQL COUNT 结果获取 ID 的 position

[英]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.我正在使用 COUNT() 创建从上到下的 30 天数据的表格表示形式。

 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.这适用于表格视图,我可以使用 ol 创建一个从 1 到 10 的编号系统。我的问题是,我希望能够告诉 position 任何给定的 id。 Eg.例如。 if I want to get the position of id9 in this count result ie 8, how do I do that?如果我想在这个计数结果中得到 id9 的 position,即 8,我该怎么做?

If you are using MySQL v8.0 or higher you can use the RANK function :如果您使用 MySQL v8.0 或更高版本,您可以使用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:对于以前版本的 mysql,您需要自己创建变量:

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.注意SELECT @rank:= 0启动变量。

Updated:更新:

To select a specific id and it's rank, you can use:对于 select 一个特定的id和它的等级,你可以使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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