Find the ranking of an integer in mysql [duplicate]

人走茶凉 提交于 2019-12-02 03:49:29

问题


Possible Duplicate:
Mysql rank function

I have the following countryTable

country  clicks
-------  ------
0        222
66       34 
175      1000
45       650

How do I get the ranking of say country 45 which is 2 in this case?


回答1:


Ordered by country ASC:

SELECT 1+COUNT(*) AS ranking
FROM countryTable
WHERE country < 45 ;

Ordered by clicks DESC:

SELECT 1+COUNT(*) AS ranking
FROM countryTable AS t
  JOIN countryTable AS c
      ON c.clicks > t.clicks
WHERE t.country = 45 ;



回答2:


You can get 2 rank as below it like below:

Select * from tabeName order by clicks limit 1,1

For 3 rank:

Select * from tabeName order by clicks limit 2,1



回答3:


SELECT *
FROM 
(
  SELECT  @ranking:= @ranking + 1 rank,
          a.country,
          a.clicks
  FROM    tableName a, (SELECT @ranking := 0) b
  ORDER BY a.clicks DESC
) s
WHERE country = 45
  • SQLFiddle Demo



回答4:


This will show the correct rank (2) for country 45. You don't specify how to rank ties, so you may want to change the comparison to suit you. Non existing countries rank as 0.

SELECT COUNT(*) rank 
FROM countryTable a
JOIN countryTable b
  ON a.clicks <= b.clicks
WHERE a.country = 45

SQLfiddle here.




回答5:


X is the rank you need to look for:

SELECT * FROM T ORDER BY clicks DESC LIMIT X-1,1



回答6:


Here's another (stunningly fast) way (albeit limited to 256 rows):

SELECT country
     , clicks
     , FIND_IN_SET(clicks,(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC) FROM country_clicks)) rank
FROM country_clicks

or, if you prefer...

SELECT FIND_IN_SET(clicks,(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC) FROM country_clicks)) rank
   FROM country_clicks
  WHERE country = 45;


来源:https://stackoverflow.com/questions/14294542/find-the-ranking-of-an-integer-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!