I have a database where records are not kept every day. However I need to calculate the balance change between dates where there are records (ignoring dates where there are no entries).
For example I would like a result that looks like this:
business_date balance prev_date prev_balance diff
2014-01-16 -2648 2014-01-13 436 -3084
2014-02-04 37 2014-01-16 -2648 2685
2014-02-11 37 2014-02-04 37 0
2014-02-12 37 2014-02-11 37 0
2014-02-21 -9633 2014-02-12 37 -9670
2014-03-03 396 2014-02-21 -9633 10029
2014-04-02 -10252 2014-03-03 396 -10648
2014-04-03 -7033 2014-04-02 -10252 3219
2014-05-21 -6849 2014-04-03 -7033 184
Unfortunately I do not know the interval between the current and previous dates, as it is always different. So I can't use something like DATE_SUB.
This is what I've tried:
select * from
(select business_date, balance
from table1
order by business_date) d
LEFT JOIN
(select business_date as prev_date,balance as prev_balance
from table2
order by business_date) a
on a.prev_date > d.business_date
But this returns only a bunch of nulls for the prev columns.
Everything I've read on this subject seems to involve creating a table of all dates, but this won't work for me as my list of dates is supposed to be incomplete, I only want to include dates for which we have records.
Any suggestions on how to approach this would be very helpful, thank you.