SQLite 运行 每日计算的产品交易总和

SQLite Running sum of transactions over products calculated daily

我有一个 table(储藏室)用作分类帐,其中仅在交易发生时随时间记录产品的添加和删除。我想每天获取曾经记录的所有产品的 运行 总和。可能有更好的方法来获得此结果,但我不想旋转 table.

我想要得到的结果是这里 table 中的结果。非常感谢!

您可以 CROSS 将递归 CTE 连接到 table 的不同产品,然后将 LEFT 连接到 table 以获得 运行 用 SUM() window 函数求和:

with dates as (
  select min(date) date from pantry
  union all
  select date(date, '+1 day')
  from dates
  where date < (select max(date) from pantry)
)
select *
from (
  select d.date, p.produce,
        sum(t.transactions) over (partition by p.produce order by d.date) running_sum
  from dates d 
  cross join (select distinct produce from pantry) p
  left join pantry t on t.date = d.date and t.produce = p.produce
)
where running_sum is not null
order by date

参见demo
结果:

> date       | produce | running_sum
> :--------- | :------ | ----------:
> 2020-01-01 | banana  |          50
> 2020-01-02 | banana  |          50
> 2020-01-03 | apple   |           5
> 2020-01-03 | banana  |          40
> 2020-01-04 | apple   |           5
> 2020-01-04 | banana  |          40
> 2020-01-05 | apple   |           5
> 2020-01-05 | banana  |          40
> 2020-01-06 | apple   |           5
> 2020-01-06 | banana  |          40
> 2020-01-07 | apple   |           3
> 2020-01-07 | banana  |          20
> 2020-01-07 | grapes  |         100
> 2020-01-08 | apple   |           3
> 2020-01-08 | banana  |          20
> 2020-01-08 | grapes  |         100
> 2020-01-09 | apple   |           3
> 2020-01-09 | banana  |          20
> 2020-01-09 | grapes  |          50
> 2020-01-10 | apple   |           3
> 2020-01-10 | banana  |          20
> 2020-01-10 | grapes  |          50
> 2020-01-11 | apple   |          -1
> 2020-01-11 | banana  |          20
> 2020-01-11 | grapes  |          50
> 2020-01-11 | melon   |           2