group by和find amount difference sql同一个表

vqlkdk9b  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(159)

我有这样一张table:

我想要的结果是:按日期对金额组求和,然后找出结果之间的差异

c6ubokkw

c6ubokkw1#

如果您使用的是mysql 8.0,那么您可以使用 lag() 达到预期的产出。

select
    date,
    amount,
    coalesce((amount - last_val), amount) as diff
from
(
  select
      date,
      amount,
      lag(amount) over (order by date) as last_val
  from
  (
      select
          date,
          sum(amount) as amount
      from myTable
      group by
          date
  ) subq
) subo
order by
    date

相关问题