我有一个表(储藏室)用作分类帐,仅当发生交易时,才会随着时间记录产品的添加和移除。我想每天获取所有产品的运行总和。可能会有更好的方法来获得此结果,但我不想透视表。
我想要得到的结果是这里表中的结果。非常感谢!
答案 0 :(得分:1)
您可以CROSS
将递归CTE
连接到表的不同乘积,然后将LEFT连接到表以使用SUM()
窗口函数获得运行总和:
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