[英]cumlative sum missing values of the month in sql
i have input data below我在下面有输入数据
date amount
01-01-2020 10
01-02-2020 15
01-03-2020 10
01-05-2020 20
01-06-2020 30
01-08-2020 5
01-09-2020 6
01-10-2020 10
select sum(date),over(partition date) from table; select sum(date),over(partition date) from table;
after add the missing month values i need output添加缺少的月份值后,我需要 output
output output
Date amount cum_sum
01-01-2020 10 10
01-02-2020 15 25
01-03-2020 10 35
01-04-2020 0 35
01-05-2020 20 55
01-06-2020 30 85
01-07-2020 0 85
01-08-2020 5 90
01-09-2020 6 96
01-10-2020 10 106
You would typically generate the dates with a recursive query, then use window functions.您通常会使用递归查询生成日期,然后使用 window 函数。
You don't tell which database you use.你不告诉你使用哪个数据库。 The exact syntax of recursive queries and date artithmetics varies across vendors, but here is what it would look like:递归查询和日期算法的确切语法因供应商而异,但如下所示:
with recursive all_dates (dt, max_dt) as (
select min(date) dt, max(date) max_dt from mytable
union all
select dt + interval '1' day, max_dt from all_dates where dt < max_dt
)
select d.dt, sum(t.amount) over(order by c.dt) amount
from all_dates d
left join mytable t on t.date = d.dt
order by d.dt
You simply want a window function:您只需要一个 window function:
select t.*, sum(amount) over (order by date)
from table t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.