0

Below is what I have

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

What I want is as below

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

NOTE:

I have code where I have created below output,

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

Code is

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

I want user 6 to have position as 5 instead of 6

2
  • Maybe adding an unique could help.
    – fortran
    Jan 16, 2012 at 10:06
  • it was a distinct, sorry, my sql gets rusty very quickly... see my answer :-)
    – fortran
    Jan 16, 2012 at 10:10

3 Answers 3

2

What about this?

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
  • Had some problem getting this to work, the difference being I'm doing it on a derived table (that is constructed from multiple table joins)
    – snowpolar
    Apr 1, 2013 at 14:14
1

Try this one -

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
0
0

I think that you could try it using variables, which looks easier. Something like this:

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

(Currently I'm unable to check MySql queries, please, excuse me if there is some error)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.