我試圖模擬MS-Excel公式與這個Excel字段: A - StudyYears 乙 - Inflation_Adjusted_Expenditures Ç - AnnualContribution d - ContributionIncrease ë - InterestIncome 的F - RunningBalance總結SQL中的4列用作相同SQL的字段?
當前的Excel光標位置:柱 - F,Row - 3 公式: F2 + E2 + C2 + B2
到MS-Access sql查詢。從不同的表中採取的領域。但是,字段RunningBalance最初是從表tblParameter字段StartingBalance中獲取的。該查詢的下一個RunningBalance記錄應該添加前一記錄中的四個字段。
由於循環引用是sql查詢中的問題,我嘗試創建一個像這樣的函數。
'*************************************************************
' FUNCTION: PREV_RUNNINGBALANCE()
' PURPOSE: Retrieve a value from a field in the previous record.
' PARAMETERS:
' StartingBalance - Starting Running Balance which is given
' RefValue - ID value
' RETURN: The computed value for the 4 field mention located in the
' previous record.
' EXAMPLE:
' =Prev_RunningBalance(StudyYears, 404585)
'**************************************************************
Function Prev_RunningBalance(RefValue As Long, StartingBalance As Long)
Dim dbs As DAO.Database
Dim rsSQL As DAO.Recordset
Dim strSQL As String
Dim vRunningBalance As Integer
On Error GoTo Err_PrevRecVal
strSQL = "Select Inflation_Adjusted_Expenditures, AnnualContribution, InterestIncome, RunningBalance FROM GenerateFundingPlanData WHERE StudyYears = " & RefValue
Set dbs = CurrentDb
Set rsSQL = db.OpenRecordset(strSQL, dbOpenDynaset)
rsSQL.FindFirst "StudyYears = " & RefValue
If Not rsSQL.NoMatch Then
'Return 0
Prev_RunningBalance = 0
End If
If rsSQL.BOF Then
Prev_RunningBalance = 0
'Prev_RunningBalance = rsSQL![Inflation_Adjusted_Expenditures] + rsSQL![AnnualContribution] + rsSQL![InterestIncome] + StartingBalance
End If
Do While Not rsSQL.BOF
' Move to the previous record.
rsSQL.MovePrevious
' Sum the fields to get the RunningBalance
' RunningBalance = Inflation_Adjusted_Expenditures + AnnualContribution + InterestIncome + CurrentRunningBalance
Prev_RunningBalance = rsSQL![Inflation_Adjusted_Expenditures] + rsSQL![AnnualContribution] + rsSQL![InterestIncome] + rsSQL![RunningBalance]
Loop
'Close Connection
rsSQL.Close
Bye_PrevRecVal:
Set rsSQL = Nothing 'Deassign all objects.
Set dbs = Nothing
Exit Function
Err_PrevRecVal:
Resume Bye_PrevRecVal
End Function
嘗試函數後,我得到一個空結果。這是我的查詢示例。
SELECT Prev_RunningBalance(a.StudyYears, 404585) as RunningBalance,
a.StudyYears FROM AnalysisYears a;
我使用正確的功能嗎?
請指出我。謝謝。
是的!這是IT!..感謝你的迴應戈爾爵士。我低估了小於等於的有用性。 – Charlesliam