I'm trying to build a personalized query for my table which consists on obtaining the latest N records for each person. My table schema is as follows:
+-----------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+-------+
| person | varchar(100) | NO | PRI | NULL | |
| time | bigint(20) unsigned | NO | PRI | NULL | |
+-----------+---------------------+------+-----+---------+-------+
For example, if I had the following data:
+---------+-------+
| person | time |
+---------+-------+
| A | 2 |
| A | 7 |
| B | 1 |
| B | 6 |
| B | 4 |
| C | 3 |
+---------+-------+
and my N = 2
, the expected result would be:
+---------+-------+
| person | time |
+---------+-------+
| A | 7 |
| A | 2 |
| B | 6 |
| B | 4 |
| C | 3 |
+---------+-------+
(Just last 2 results for each person, order by person asc, time desc)
I know I can get all the person names first and select/order/limit them one by one, but I'm curious to know if I could to this in one query, and let the DBMS do the hard work. For N = 1
, I successfully used max and group by statements:
SELECT person, max(time) as time FROM table GROUP BY person ORDER BY person ASC, time DESC
But I don't know how to extend it for greater values of N. Can you please help me?