Search code examples
mysqlsqlselect-query

Get the user with the 1000th point (SQL query)


I am trying to just do a query that will illustrate which student from school_id 1 has got the 1000th point - in this case it is 'Sharon'

+++++++++++++++++++++++++++++++++++++
# id # school_id # student # points #
#  1 #     1     #  Harry  #   100  #
#  2 #     1     #  Bob    #   200  #
#  3 #     1     #  Jamie  #   150  #
#  4 #     1     #  Lee    #   200  #
#  5 #     1     #  John   #   200  #
#  6 #     1     #  Sharon #   170  #
#  7 #     2     #   Tim   #  2000  #
+++++++++++++++++++++++++++++++++++++

I had a crack with the following query but it doesn't return what I would expect:

SELECT
  SUM(points) as pointSum, student
FROM testing
GROUP BY school_id;

I would expect a result like this...

++++++++++++++++++++++++++++++++++++++++
# id # school_id # student # pointsSum #
#  6 #     1     #  Sharon #   1020    #
++++++++++++++++++++++++++++++++++++++++

Solution

  • Use a derived table to calculate SUM of points for a user and the preceding users (id-wise).

    select name, sumpoints
    from 
    (
    select id, name, (select sum(points) from tablename t2
                      where t2.id <= t1.id) sumpoints AND t2.school_id = 1
    from tablename t1
    ) dt
    where sumpoints >= 1000
    order by id
    limit 1