mysql - 从表中选择最新的2条 “group/batch”记录

标签 mysql sql select

我有类似这个 mysql 表的数据:

id  customer_id  int_proc   inventory
1   A           1           1   
2   A           4           1
3   A           5           1
4   A           0           2
5   A           5           2
6   A           6           2
7   B           6           1       
8   B           7           1
9   B           9           1
10  B           9           2
11  B           9           2
12  C           22          1

我想从每个库存的最新 2 个 int_proc 值中获取所有数据,其中 customer_id 为 A 和 B。 我的结果应该是这样的:

id  customer_id  int_proc   inventory
2   A           4           1
3   A           5           1
5   A           5           2
6   A           6           2
8   B           7           1
9   B           9           1
10  B           9           2
11  B           9           2

非常感谢任何帮助。

最佳答案

您可以使用 Mysql 的用户定义变量,并对同一客户组中每个客户和每个库存的行进行排名,下面的查询将给出 2 个最新的 int_proc每个库存和相同的客户组,如果您想获取最新的 n 条记录,只需将 where 子句更改为 where t2.r <= n

select 
t2.id,
t2.customer_id,
t2.int_proc, 
t2.inventory
from (
select t.*,
@r:= case when @g = t.customer_id
     then
          case when @sg = t.inventory 
          then  @r+1 
          else 1 end 
      else 1 end r,
@g:= t.customer_id g,
@sg:= t.inventory sg
from test t
cross join (select @g:=null,@sg:=null,@r:=null) t1
  where t.customer_id in('A','B')
order by t.customer_id,t.inventory,t.int_proc desc
  ) t2
where t2.r <= 2
order by id

Fiddle Demo

编辑重复值

如果int_proc有重复的行您必须添加另一个子案例语句来检查重复值并对它们进行相应的排名

select 
t2.id,
t2.customer_id,
t2.inventory,
t2.int_proc
from (
select t.*,
@r:= case when @g = t.customer_id
     then
          case when @sg = t.inventory 
          then 
            case when @sr <> t.int_proc
            then  @r+1 
            else @r end 
          else 1 end 
      else 1 end r,
@g:= t.customer_id g,
@sg:= t.inventory sg,
@sr:= t.int_proc sr
from test t
cross join (select @g:=null,@sg:=null,@r:=null,@sr:=null) t1
  where t.customer_id in('A','B')
order by t.customer_id,t.inventory,t.int_proc desc
  ) t2
 where t2.r <= 2
order by id

Fiddle Demo 2

关于mysql - 从表中选择最新的2条 “group/batch”记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25823413/

相关文章:

mysql - 如何使用SQL查询逐年获取总工资?

php - 使用 PHP 将图像 blob 从 mysql 数据行插入 mysql 数据库

具有多个条件的 SQL 查询 group by

SQL Server 2005 : Wrapping Tables by Views - Pros and Cons

合并两个表然后应用计数的sql查询

dataframe - Julia DataFrame 上的多列选择

php - MySQL 查询表单数据

php - 减少 PHP 中的重复代码

php - mysql_num_rows 和条件

c# - 使用 Linq(?) 从列表中的列表中获取属性