Finding the minimum balance given a time frame
What is the best method by which I can calculate the minimum balance given a time frame? In my database, I have a deposit column and a withdraw column and date column at which they are done.
Update
Suppose on 1开发者_StackOverflow社区/1, the balance is 300. On 1/2, 300 is deposited with total of 600. On 1/15, 200 is withdrawn leaving a balance of 400. On 1/25, further withdrawal of 300 is made and the balance goes down to 100. On 1/28, 800 is deposited and balance total to 900. If on 1/31 I were to calculate the minimum balance for that month, I should get 100. Any ideas?
Use windowing functions to build the running balance, then extract the minimum out of each time interval like this:
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
Result:
month minimum_balance
2010-01-01 00:00:00-06 100
Loop through each entry in the database for every day that there was a deposit/withdrawal and store the lowest number in a variable. If the number for the day being checked is lower, replace the variable with that number.
精彩评论