mysql - Get the latest N results for each person -
i'm trying build personalized query table consists on obtaining latest n records each person. table schema follows:
+-----------+---------------------+------+-----+---------+-------+ | field | type | null | key | default | | +-----------+---------------------+------+-----+---------+-------+ | person | varchar(100) | no | pri | null | | | time | bigint(20) unsigned | no | pri | null | | +-----------+---------------------+------+-----+---------+-------+
for example, if had following data:
+---------+-------+ | person | time | +---------+-------+ | | 2 | | | 7 | | b | 1 | | b | 6 | | b | 4 | | c | 3 | +---------+-------+
and n = 2
, expected result be:
+---------+-------+ | person | time | +---------+-------+ | | 7 | | | 2 | | b | 6 | | b | 4 | | c | 3 | +---------+-------+
(just last 2 results each person, order person asc, time desc)
i know can person names first , select/order/limit them 1 one, i'm curious know if in 1 query, , let dbms hard work. n = 1
, used max , group statements:
select person, max(time) time table group person order person asc, time desc
but don't know how extend greater values of n. can please me?
ok, found solution using @rudie link:
select * ( select a.* points left join points a2 on a.person= a2.person , a.time <= a2.time group person, time having count(*) <= 2) order person asc, time desc;
live example: http://sqlfiddle.com/#!2/58026/2
it's working well. thank contributions!
Comments
Post a Comment