If I am understanding correctly...
Your goal: Display players (i.e. id_person
) in DESC
order based on how many points
that person makes in his/her best 28 games.
Here is a query that potentially does that:
SELECT id_person, sum(points) as s
FROM (
SELECT id_person,
points,
@rownum := if(@person = id_person, @rownum + 1, 1) as pointRank,
@person := id_person as dummy
FROM (SELECT id_person, points
FROM ranking
WHERE id_open >= 847 and id_club = 2 and id_person != '91'
ORDER BY id_person, points DESC
) as q1,
(SELECT @rownum := 0) as r,
(SELECT @person := '') as s
) as q2
WHERE pointRank <= 28
GROUP BY id_person
ORDER BY s DESC;
SQL Fiddle (Note: leaves out q1's WHERE
clause for convenience)
Subquery q1 explanation:
- Filters out rows based on
id_open
, id_club
, and id_person
.
- Then, orders based on
id_person
(implicitly ASC
) and points
(explicitly DESC
).
- Finally, selects the
id_person
and points
fields.
Note: MySQL Group By's are a little special - aggregates will work, but if selecting non-aggregates, a random row will be selected for the group by, not all rows (MYSQL-Group-By-returns-only-first-row)
Subquery q2 explanation:
- Adds in
rownum
and person
variables to keep track of ranking of game. (generate-column-containing-record-index-in-table)
- Needs to use the
(SELECT @rownum := 0) as r
and (SELECT @person := '') as s
to set the variables. (These variables could be set outside too.)
if(@person := id_person, @rownum + 1, 1)
is necessary to reset the ranking of games per person.
Note: Important to initialize the person
variable to an empty string, as opposed to 0. Not too sure why, but if you do not, then it will not reset the rownum
variable correctly.
Overall query explanation:
- All row numbers (i.e.
pointRank
) less than or equal to 28 (basically, the 28 best point scores per id_person
) are kept.
- After this filtering, each
id_person
will be grouped again.
- Finally, the top 28 games'
points
will be summed up and labeled as s
, and these pairs (id_person
,s
) will be ordered from highest to lowest.
Here is another StackOverflow question with a good article link inside (highly recommended read): (limit-within-group)
Note: I cannot guarantee this will work though, since I do not know what your table looks like. That information would help.