MySQL选择总和,但最后三个记录

问题描述

我的表格中包含客户日期和金额字段 我想对按客户分组的金额进行汇总,但每个客户的最后两个金额(按日期) 样本数据

 customer     date               amount
  a           2020-10-1             100
  a           2020-10-2             150
  a           2020-10-3             30
  a           2020-10-4             20
  b           2020-10-1             1
  b           2020-10-5             13
  b           2020-10-7             50
  b           2020-10-9             18

所需结果

  Customer    Amount
   A          150
   B           14

类似

select Customer,SUM(amount- last 2 amount)
From TableA
Group By Customer

解决方法

一个选项使用MySQL 8.0中提供的窗口函数:

select customer,sum(amount) total_amount
from (
    select a.*,row_number() over(partition by customer order by date desc) rn
    from tablea a
) a
where rn > 2
group by customer

在早期版本中,替代方法使用相关子查询,该子查询返回每个客户的第三个最新日期以进行过滤:

select customer,sum(amount) total_amount
from tablea a
where date <= (select a1.date from tablea a1 where a1.customer = a.customer order by a1.date desc limit 2,1)
group by customer