据我所知,您不能在域聚合函数中引用多个表或查询。正如 grazird 所说,这些表有什么关系?假设它在 tblMain ID 上,您可以构建一个名为 qryMainOffice 的查询,SQL(SQL 视图,查询设计窗口)看起来像:
SELECT [tblMain].[Revenue],[tblMain]![Quarter],[tblMain]![Region],
[tblOffice]![Location]
FROM tblMain
INNER JOIN tblOffice
ON tblMain.ID = tblOffice.MainID
然后 DSum 将是(删除换行符):
=NZ(DSum("[Revenue]","qryMainOffice",
"[Quarter]=3 AND [Region]='NorthEast' AND [Location]='NewYork'"),"Not found")
您还可以在 VBA 中使用记录集或查询来返回值。
编辑重新评论
要在 VBA 中使用上述内容,您需要添加参数或使用字符串:
''Reference: Microsoft DAO 3.x Object Library
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL as String
Set db= CurrentDB
strSQL = "SELECT Sum(t.[Revenue]) As TotalNY" _
& "FROM tblMain t " _
& "INNER JOIN tblOffice o " _
& "ON t.ID = o.MainID " _
& "WHERE t.[Quarter]=3 AND t.[Region]='NorthEast' " _
& "AND o.[Location]='NewYork' " _
'' I have use aliases for simplicity, t-tblMain, o-tblOffice
'' If you wish to reference a control, use the value, like so:
'' & " AND [Location]='" & Me.txtCity & "'"
'' Dates should be formated to year, month, day
'' For joins, see http://www.devshed.com/c/a/MySQL/Understanding-SQL-Joins/
Set rs = db.OpenRecordset strSQL
If Not rs.EOF Then
Me.txtAnswer = rs!TotNY
Else
Me.txtAnswer = "N/A"
End If
您还可以使用不同的查询来返回可以用列表框或子表单显示的多个结果:
strSQL = "SELECT TOP 5 o.[Location]," _
& "Sum(t.[Revenue]) AS TotRevenue" _
& "FROM tblMain t " _
& "INNER JOIN tblOffice o " _
& "ON t.ID = o.MainID " _
& "WHERE t.[Quarter]=3 AND t.[Region]='NorthEast' " _
& "GROUP BY o.[Location]"
以上将返回东北地区所有地点的第三季度收入。如果您想要每个组的最高值,您正在查看一个更复杂的查询,我将暂时离开。