在给定时间范围内,我可以用什么方法计算最小余额?在我的数据库中,我有一个存款列和一个撤销列和日期列,完成它们。
的更新 的
假设在1/1,余额为300.在1/2,300存入总计600.在1/15,200撤回,余额为400.在1/25,进一步撤回300在1月28日,800存入,余额总计为900.如果在1/31我计算当月的最低余额,我应该得到100.任何想法?
答案 0 :(得分:2)
使用窗口函数来构建运行余额,然后从每个时间间隔中提取最小值,如下所示:
with cte_transaction_data as
(
select 300 as deposit, null as withdraw, date '01/02/2010' as transaction_date union all
select null, 200, date '01/15/2010' union all
select null, 300, date '01/25/2010' union all
select 800, null, date '01/28/2010'
)
select
month,
min(balance) as minimum_balance
from
(
select
transaction_date,
date_trunc('month', transaction_date) as month,
300
+ coalesce(sum(deposit) over(order by transaction_date rows between unbounded preceding and current row), 0)
- coalesce(sum(withdraw) over(order by transaction_date rows between unbounded preceding and current row), 0) as balance
from cte_transaction_data
) as running_balance
group by
month
order by
month
结果:
month minimum_balance
2010-01-01 00:00:00-06 100
答案 1 :(得分:1)
在存储/取款的每一天循环遍历数据库中的每个条目,并将最小的数字存储在变量中。如果要检查的日期数较低,请将该变量替换为该数字。