I have a temp table holding a result of balance changes to an account based on each day.
DateValue DailyAmount
---------- ---------------------------------------
2014-04-21 0.00
2014-04-22 606.28
2014-04-23 -70.00
2014-04-24 -86.96
2014-04-25 -101.01
2014-04-26 -27.00
2014-04-27 0.00
2014-04-28 -75.00
2014-04-29 -12.00
2014-04-30 0.00
2014-05-01 -164.00
2014-05-02 -49.95
2014-05-03 0.00
2014-05-04 0.00
2014-05-05 -140.00
2014-05-06 538.23
2014-05-07 -70.00
2014-05-08 223.04
2014-05-09 0.00
2014-05-10 -50.00
2014-05-11 0.00
2014-05-12 -140.00
2014-05-13 -12.00
2014-05-14 0.00
2014-05-15 6179.81
I need to select from this table, adding a running balance, based on an opening balance variable I have.
Is it safe to select, and join to it's self somehow with Dateadd(DAY, -1, Datefield)?
My failed attempt (Wrong results) was this:
SELECT DateValue, ISNULL(r.Amount,0) AS DailyAmount, SUM(ISNULL(r.Amount,0))
FROM calendar c
LEFT JOIN @Result r
ON r.TheDate = c.DateValue
LEFT JOIN @Result r2
ON r2.TheDate = DATEADD(day, -1, r.TheDate)
WHERE c.DateValue BETWEEN @Start AND @End
GROUP BY c.DateValue, r.Amount
SQL Version is Microsoft SQL Server 2008 R2 (SP2)