在MySQL中排名联合职位

时间:2012-01-16 10:03:12

标签: mysql

以下是我的内容

  userid score 
    1       8    
    2       5    
    3       4    
    4       4    
    5      10    
    6       3  

我想要的是如下

userid score position
    5      10     1
    1       8     2
    2       5     3
    3       4     4
    4       4     4
    6       3     5

注意:

我在下面的输出中创建了代码,

userid score position
    5      10     1
    1       8     2
    2       5     3
    3       4     4
    4       4     4
    6       3     6

代码是

SELECT userid, score, 
(SELECT COUNT(*) FROM fschema.mytab3 u2 
WHERE 
u2.score > u1.score) + 1 AS position FROM fschema.mytab3 u1
ORDER BY position

我希望用户6将position设为5而不是6

3 个答案:

答案 0 :(得分:2)

这个怎么样?

SELECT userid, score, 
(SELECT COUNT(distinct u2.score) FROM fschema.mytab3 u2 
WHERE 
u2.score > u1.score) + 1 AS position FROM fschema.mytab3 u1
ORDER BY position

答案 1 :(得分:1)

试试这个 -

SELECT
  *,
  @r:=IF(@score IS NULL OR @score <> score, @r+1, @r) position, @score:=score
FROM
  fschema.mytab3,
  (SELECT @r:=0, @score:=NULL) t
ORDER BY
  score DESC, userid

答案 2 :(得分:0)

我认为您可以尝试使用变量,这看起来更容易。像这样:

SELECT userid, score, @rownum:=@rownum+1 as position
FROM fschema.mytab3 u1, (SELECT @rownum:=0) r
ORDER BY score;

(目前我无法检查MySql查询,请原谅,如果有错误的话)

相关问题