mysql - 获取每个产品的前两条记录

标签 mysql greatest-n-per-group

我有一个包含如下三个字段的表格,每个产品都有多条记录。我想知道如何为每种产品获取前 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) 

关于mysql - 获取每个产品的前两条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7261058/

相关文章:

mysql - 当选择字段使用条件时对其进行索引?

mysql - 如何在 MySQL 中使用 case 获取特定字段的计数

mysql - 查询未使用 max 函数带来关联值(Northwinds 数据库)

mysql - 如何构建 SQL 来查找每个产品在不同日期和时间的最大产品数?

sql-server - Microsoft SQL 查询 - 从第二个表中返回最后一条记录

mysql - Laravel Eloquent 连接多个表

php - 如何选择 MySQL 中最常见的值?

mysql - 我需要什么样的 MySQL 连接?

mysql - 选择最大值按两列分组的行

mysql - SQL - 选择 'n' 组中最大的元素