Well, I had to admit defeat.
I couldn't get the results you wanted using strictly SQL.
But I was able to with a query and a UDF.
I made a table but didn't use spaces in the table name; I think I added all of the spaces back.
Here is the code:
Code:
Public Function CalcBalance(ThisDate As Date, pProduct As String) As Integer
Dim r As DAO.Recordset
Dim sSQL As String
Dim RunningBal As Integer
Dim ThisOnHand As Integer
Dim ThisDemand As Integer
'set default return value
CalcBalance = 0
'initalize variables
RunningBal = 0
' Open recordset
sSQL = "SELECT OnHand, Demand"
sSQL = sSQL & " FROM [tblStock Array]"
sSQL = sSQL & " WHERE [strProductID] = '" & pProduct & "' AND [BeginDate]<= #" & ThisDate & "#;"
Debug.Print sSQL
Set r = CurrentDb.OpenRecordset(sSQL)
If Not r.BOF And Not r.EOF Then
' Populate the recordset
r.MoveLast
r.MoveFirst
Do While Not r.EOF
RunningBal = RunningBal + Nz(r!OnHand, 0) - Nz(r!Demand, 0)
If RunningBal < 0 Then
RunningBal = 0
End If
r.MoveNext
Loop
End If
r.Close
CalcBalance = RunningBal
Set r = Nothing
End Function
Here is the query:
Code:
SELECT [tblStock Array].strProductID, [tblStock Array].BeginDate, [tblStock Array].OnHand, [tblStock Array].Demand, CalcBalance([begindate],[strProductID]) AS Balance
FROM [tblStock Array]
ORDER BY [tblStock Array].strProductID, [tblStock Array].BeginDate;
And the results
Attachment 14124