开发者

Get top two records for each product

开发者 https://www.devze.com 2023-04-02 02:11 出处:网络
I have a table with three fields as below, each product has multiple records. I\'m wondering how can I fetch top 2 for each product? I sorted my records by time field already.

I have a table with three fields as below, each product has multiple records. I'm wondering how can I fetch top 2 for each product? I sorted my records by time field already.

eventId productId   t开发者_开发问答ime
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

Can any expert help me to get top 2 records for EACH product?


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) 


I don't have an SQL editor at hand, but it could probably look like this :

SELECT * FROM theTable WHERE eventId IN 
    (SELECT TOP(2) eventId FROM theTable as innerTable 
        WHERE innerTable.productId = theTable.productId)

Replace "theTable" with your table name.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号