【问题标题】:Mysql Select Sum but last three recordsMysql选择总和但最后三条记录
【发布时间】:2020-10-29 11:47:07
【问题描述】:

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

 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 sql sum greatest-n-per-group sql-limit


【解决方案1】:

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

【讨论】:

  • 这给出了错误:1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以获取正确的语法,以便在第 3 行 @GMB 的 '(partition by customer order by date desc) rn from table t' 附近使用
  • @BeidreAhmed:您正在运行 MySQL 8.0 之前的版本。我用替代方法编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多