Sql-server – I have a beginning balance I need to calculate ending balance running total by month rows

running-totalssql serversql server 2014

I have been searching this site and others trying to find an answer to this. I tried various things but cannot get my head around an answer so here goes.
Here my data:
beg_image

What I need is to start with the begbal of each Acct and add the debits, subtract the credits and produce an ending balance of that month (row). When the Acct changes, pick up the new begbal and start again. With the data it should look like this:
![end_image

I can get a running total on the debits and credits by doing this:

SELECT
pph.Acct,
pph.Year, 
pph.Prd,
pph.begbal,
pph.debit,
pph.credit,
SUM(pph.debit+pph.credit) OVER (PARTITION BY pph.Acct ORDER BY pph.Year, pph.Prd) AS endbal
FROM GL_PeriodPostingHistory pph

What I want to do is

If Acct <> prevoius Acct

then Sum( begbal+debit-credit)

else Sum(previous endbal+debit-credit) as endbal

and I just can't figure out how.

Best Answer

You can use the FIRST_VALUE window function along with SUM(pph.debit-pph.credit) to get your desired output.

SELECT
pph.Acct,
pph.Year, 
pph.Prd,
pph.begbal,
pph.debit,
pph.credit,
FIRST_VALUE(pph.begbal) OVER (PARTITION BY pph.Acct ORDER BY pph.Year, pph.Prd)
    + SUM(pph.debit-pph.credit) OVER (PARTITION BY pph.Acct ORDER BY pph.Year, pph.Prd) AS endbal
FROM dbo.GL_PeriodPostingHistory pph;

db fiddle link.

Thanks to HandyD for the sample data written as T-SQL.