I think this will get you what you want with however a rolling date range you are concerned with... I've tested by creating my own "invoice" table with the two columns identified. It actually was quite simple with the utilization of @ mySQL variables that can be used inline in the query... The only thing is, there is now true way to know what an "opening" balance is, so I've set the initial startup value of zero then adjust from that.
The kicker is the "PreAgg" query to just aggregate by the date itself of in/out. Then, by ordering that result in date order, the @ sql variable kicks in.
select
PreAgg.PostDate,
@PrevBal as BegBal,
PreAgg.OutFlows,
PreAgg.InFlows,
@PrevBal := @PrevBal + PreAgg.OutFlows + PreAgg.InFlows as EndBal
from
( select
i.postdate,
sum( if( i.amount < 0, i.amount, 0 ) ) as OutFlows,
sum( if( i.amount > 0, i.amount, 0 ) ) as InFlows
from
invoice i
where
i.postdate between date_sub( now(), interval 2 month )
and date_add( now(), interval 1 month )
group by
i.postdate
order by
i.postdate ) as PreAgg,
( select @PrevBal := 0.00 ) as SqlVars
However, even though I've given a 3 month window (-2 months, +1 month), I don't think that really makes sense as the future postings will not have happened yet... what may be more important is to just have
where
i.postdate > date_sub( now(), interval 3 month )
which will get the last 3 months from current date/time.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…