我有一个包含三个字段的表,如下所示,每个产品都有多个记录。我想知道如何才能获得每件产品的前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个记录吗?
答案 0 :(得分: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)
答案 1 :(得分:0)
我手头没有SQL编辑器,但它可能看起来像这样:
SELECT * FROM theTable WHERE eventId IN
(SELECT TOP(2) eventId FROM theTable as innerTable
WHERE innerTable.productId = theTable.productId)
将“theTable”替换为您的表名。