What's the best way I'm able to calculate the minimum balance given a time period? During my database, I've got a deposit column along with a withdraw column and date column where they're done.
Suppose on 1/1, the total amount is 300. On 1/2, 300 is deposited with total of 600. On 1/15, 200 is withdrawn departing an account balance of 400. On 1/25, further withdrawal of 300 is created and also the balance goes lower to 100. On 1/28, 800 is deposited and balance total to 900. If on 1/31 I would calculate the minimum balance for your month, I ought to get 100. Any ideas?
Use windowing functions to construct the running balance, then extract the minimum from every time interval such as 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
month minimum_balance 2010-01-01 00:00:00-06 100
Loop through each entry within the database for each day that there is a first depositOrdrawback and keep cheapest number inside a variable. When the number during the day being checked is gloomier, replace the variable with this number.