我怎么能用SQL做排名

时间:2012-10-18 16:42:15

标签: mysql sql

我有一个带有id和值的表。 如何按照其值来对desc的顺序进行排序? 我想做的是:

SELECT id FROM table ORDER BY value DESC

我希望它告诉我例如id = 4

的位置

非常感谢您的回答!

2 个答案:

答案 0 :(得分:2)

MySQL没有分析功能,因此您必须使用user variables

SELECT   @r:=@r+1 AS rank, id
FROM     table, (SELECT @r:=0) init
ORDER BY value DESC

要获取特定记录的排名,请将其包装在外部查询中:

SELECT rank FROM (
  SELECT   @r:=@r+1 AS rank, id
  FROM     table, (SELECT @r:=0) init
  ORDER BY value DESC
) t WHERE id = 4

为了保存MySQL不必要地计算表中每个记录的等级,你可以添加一个过滤器:

SELECT rank FROM (
  SELECT   @r:=@r+1 AS rank, table.id
  FROM     table,
           (SELECT value FROM table WHERE id=4) t,
           (SELECT @r:=0) init
  WHERE    table.value >= t.value
  ORDER BY table.value DESC
) t WHERE id = 4

答案 1 :(得分:1)

Eggyal的解决方案不是rank,而是row_number(这些实际上有意义,因为它们是SQL标准的一部分)。

我认为以下是MySQL中的dense_rank

SELECT   @r:=@r+1 AS rank, id
FROM     (select id, count(*) as cnt
          from table t
          group by id
         ),
         (SELECT @r:=0) init
ORDER BY value DESC

rank有点困难。 。 。我认为以下内容可行:

SELECT   @r:=@r+1-offset AS rank, id
FROM     (select id, count(*) as cnt
          from table t
          group by id
         ),
         (SELECT @r:=0, count(*)-1 as offset
          from table t
          group by id
          order by count(*) desc
          limit 1
         ) init
ORDER BY value DESC