我有一个包含三个字段的表,如下所示,每个产品都有多个记录.我想知道如何才能获得每件产品的前2名?我已按时间字段对记录进行了排序.
eventId productId time 1 10568 2011-08-30 15:06:57 2 10568 2011-08-30 15:06:56 3 10568 2011-08-30 15:06:53 4 10568 2011-08-30 15:06:50 5 10111 2011-08-30 15:06:56 6 10111 2011-08-30 15:06:53 7 10111 2011-08-30 15:06:50 8 10000 2011-08-30 15:06:56 9 10000 2011-08-30 15:06:53 10 10000 2011-08-30 15:06:50
任何专家都可以帮助我获得每个产品的前2个记录吗?
最佳答案
select *
from table t
inner join (select distinct productId as productId from table) table2
on (table2.productid = t.productid
where table.time >= (select time from table innertable
where productid = t.productid
order by time desc
limit 1 offset 1)