Mysql Select 对最后三个记录求和

Mysql Select Sum but last three records

我有 table 字段客户日期和金额 我想按日期汇总除每个客户的最后两个金额外按客户分组的金额 样本数据

 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

一个选项使用 window 函数,在 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

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

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