2

可能重复:
Mysql rank 函数

我有以下国家表

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

在这种情况下,我如何获得国家 45 的排名,即 2?

4

6 回答 6

2

订购者country ASC

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

订购者clicks DESC

SELECT 1+COUNT(*) AS ranking
FROM countryTable AS t
  JOIN countryTable AS c
      ON c.clicks > t.clicks
WHERE t.country = 45 ;
于 2013-01-12T15:01:13.500 回答
2

您可以获得 2 等级,如下所示:

Select * from tabeName order by clicks limit 1,1

3级:

Select * from tabeName order by clicks limit 2,1
于 2013-01-12T15:01:24.687 回答
1

这将显示国家 45 的正确排名 (2)。您没有指定如何对平局进行排名,因此您可能需要更改比较以适合您。不存在的国家排名为 0。

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

SQLfiddle 在这里

于 2013-01-12T15:08:47.793 回答
1
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
于 2013-01-12T15:01:55.860 回答
0

X是您需要寻找的等级:

SELECT * FROM T ORDER BY clicks DESC LIMIT X-1,1
于 2013-01-12T15:04:21.450 回答
0

这是另一种(惊人的快速)方式(尽管限制为 256 行):

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

或者,如果您愿意...

SELECT FIND_IN_SET(clicks,(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC) FROM country_clicks)) rank
   FROM country_clicks
  WHERE country = 45;
于 2013-01-12T15:08:26.903 回答