-3

I have a DB Table user_points which contains user's points and I am trying to calculate ranking based on points. It is working fine for all users except users having 1 point.

If user have 1 point it is showing it's rank as 0 but it should display it's rank as last or in last numbers like: 12083 etc.

Higher points are, ranking should be higher as well. For example:

1000 points = rank 1

1 point = rank 1223

Following is the query.

SELECT id, mobileNo, points, 
       FIND_IN_SET( points, (SELECT GROUP_CONCAT( points ORDER BY points DESC ) 
                             FROM users_points )) AS rank 
FROM users_points 
WHERE mobileNo = '03214701777'

What should I change to fix it?

Community
  • 1
  • 1
Noman Ali
  • 3,160
  • 10
  • 43
  • 77

1 Answers1

3
SELECT a.id, a.mobileNo, a.points, 
   IFNULL((SELECT COUNT(*) AS rank
    FROM users_points b
    WHERE b.points<a.points), 0)+1 as rank
FROM user_points a
WHERE a.mobileNo  = '03214701777'

Seems to be what you are looking for. While it is still very innefficient it is better than your approach using FIND_IN_SET(). If you really want to use FIND_IN_SET() then you need to pad the scores to a consistent width and divide by the width+1 to get the rank.

symcbean
  • 47,736
  • 6
  • 59
  • 94