如何连续排名

时间:2015-08-03 06:58:02

标签: sql

我有一张像

这样的表格
   name          age
   -----------------
   jagga         25 
   lipu          25 
   aswinee       24 
   lisu          23 
   ankita        25 
   jhon          23 

我希望像

一样
   name         age     rank
   -------------------------
   ankita       25      1 
   jagga        25      2  
   lipu         25      3 
   aswinee      24      4 
   jhon         23      5  
   lisu         23      6  

nameage必须有order by条款,但rank将从1开始计算。

5 个答案:

答案 0 :(得分:2)

我们不知道您使用的是哪个dbms,所以
MySQL

SET @id := 0;
SELECT test.name
,      test.age
,      @id := @id + 1 AS rank
FROM   test
ORDER BY age desc, name;

MS SQL Server /的 Oracle / Postgresql

SELECT name
,      age
,      ROW_NUMBER() OVER(ORDER BY age DESC, name) AS rank   
FROM   test
ORDER BY age desc, name

答案 1 :(得分:0)

仅提及排名函数“row_number”必须具有ORDER BY子句。我同意horsenoname

select name,age,row_number() over (order by age desc,name) as rank from mytable order by age desc,name

答案 2 :(得分:0)

请参阅@ a_horse_with_no_name的评论。

如果您的RDBMSmysql

select
    t.name,
    t.age,
    @rank := @rank + 1 as rank
from (
    SELECT name, age
    FROM tbl order by name
) as t,
(select @rank := 0) as r

答案 3 :(得分:0)

使用分析函数Rank

SELECT NAME, AGE, RANK() OVER (ORDER BY AGE DESC, NAME) Rank FROM STUDENTS;

答案 4 :(得分:0)

选择agerow_number()age结束(按rank desc排序)为table_name  来自age desc,name

$.ajax({ url: 'JsonProcessor.do', type: 'post', dataType: 'json', data: { loadProds: 1, test: JSON.stringify(StateObject) }, ... 订单