I have a points system setup on my site, where every single point accumulated is logged in the points table. The structure is simple, p_userid, p_points (how many points accumulated during this action), and p_timestamp.
I wanna display top 3 point accumulating users, for each month. So essentially, it should sum the p_points table for the month, for each user id, and display the top 3 users, grouped into months. The user ids will be joined to a users table, to get actual user names.
What would be the best way to do it? I use php/mysql.
EDIT:
As a possible solution, I could create another column, and log YYYY-MM into it, and simply group it based on that, but thats more data I gotta log, for an already huge table.
EDIT 2:
Data stored as such
INSERT INTO `points` (`point_userid`, `point_points`, `point_code`, `point_date`) VALUES
(8465, 20, 3, 1237337627),
(46745, 20, 3, 1237337678),
(7435, 20, 3, 1237337733),
(46565, 20, 3, 1237337802),
(4466, 20, 3, 1237337836),
(34685, 20, 3, 1237337885),
(8544, 20, 3, 1237337908),
(6454, 20, 3, 1237337998),
(45765, 20, 3, 1237338008),
(3476, 20, 3, 1237338076);
This isn’t easy in MySQL.
First you need to create a table of variables, one for storing the current group, and one for storing the current row number in the group. Initialize them both to NULL.
Then iterate group by month and select all rows ordered by score and select the current rown number and increase it. If the group changes, reset the row number to one.
Then put all this in a subselect and in the outer select, select all rows with rownumber <= 3.
You could use this query:
Result:
Test data: