Используйте функции управления окнами для построения текущего баланса, а затем извлекайте минимум из каждого временного интервала следующим образом:
<code>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
Результат:
<code>month minimum_balance
2010-01-01 00:00:00-06 100