I have a MySql table with sample data like this:
+---------+---------+--------+---------------------+
| id | user_id | scores | created_at |
+---------+---------+--------+---------------------+
| 1 | 1 | 10 | 2012-12-14 02:40:37 |
| 2 | 1 | 20 | 2012-12-14 02:55:54 |
| 3 | 1 | 10 | 2012-12-14 01:17:21 |
| 4 | 2 | 30 | 2012-12-13 01:54:47 |
| 5 | 2 | 55 | 2012-12-15 00:34:39 |
| 6 | 2 | 10 | 2012-12-14 00:20:21 |
+---------+---------+--------+---------------------+
And I need to query it, so that scores would be summed per user and per hour. One hour here is assumed to be created_at with skipped minutes and seconds (04:00:00 to 04:59:59 etc.). So something like this:
+---------+--------+---------------------+
| user_id | scores | created_at |
+---------+--------+---------------------+
| 1 | 30 | 2012-12-14 02:00:00 |
| 1 | 10 | 2012-12-14 01:00:00 |
| 2 | 30 | 2012-12-13 01:00:00 |
| 2 | 55 | 2012-12-15 00:00:00 |
| 2 | 10 | 2012-12-14 00:00:00 |
+---------+--------+---------------------+
In this sample data only first user played more than once during one hour (2012-12-14 02:00:00) – so his scores during that hour were summed up.
From summed scores I need only top score for each user (to create ranks). So final, expected result should be:
+---------+---------------------+---------------------+
| user_id | top_scores_per_hour | hour |
+---------+---------------------+---------------------+
| 1 | 30 | 2012-12-14 02:00:00 |
| 2 | 55 | 2012-12-15 00:00:00 |
+---------+---------------------+---------------------+
I have an Idea how to do part of this… I could deal with rest outside of database, but I really wonder – how could I query this with SQL ?
Output