使用分组依据在Access查询中运行总和

我无法获得一笔总和在access查询中工作。我有一个管道系统,正在尝试总结通过管道网络的流量Q。我一直在尝试根据group_by ID_downstream和Q_total上的DSum进行求和。但是,我不断收到错误或错误的输入。

所需的输出是,我可以看到通过网络累积的流量,如表和图片所示。

使用分组依据在Access查询中运行总和

使用分组依据在Access查询中运行总和

fuchen333 回答:使用分组依据在Access查询中运行总和

您有几种选择。但是,不会这样做,那是仅使用SQL的递归查询。访问不可上当,并且会要求提供循环引用。您唯一的机会是创建仅解决有限数量的级别(例如8或10)的查询。

但是您可以在域聚合函数(如DLookup)中涵盖递归调用。但是,这非常慢,因为DLookup调用查询将针对每条记录运行。对于许多记录,这很可能是不可接受的。

对于无限数量的级别,最快的方法是创建一个查找功能,该功能可以遍历每条记录。这可以输出记录的级别,也可以输出由记录的键和上面所有键组成的复合键。

由于查找函数将为每个调用使用相同的记录集,因此可以使其变为静态,并且(对于JET / ACE)可以通过使用Seek来定位记录。

以下是一个示例,可以为您提供一个想法:

Function RecursiveLookup(ByVal lngID As Long) As String

  Static dbs      As Database
  Static tbl      As TableDef
  Static rst      As Recordset

  Dim lngLevel    As Long
  Dim strAccount  As String

  If dbs Is Nothing Then
    ' For testing only.
    ' Replace with OpenDatabase of backend database file.
    Set dbs = CurrentDb()
    Set tbl = dbs.TableDefs("tblAccount")
    Set rst = dbs.OpenRecordset(tbl.Name,dbOpenTable)
  End If

  With rst
    .Index = "PrimaryKey"
    While lngID > 0
      .Seek "=",lngID
      If Not .NoMatch Then
        lngLevel = lngLevel + 1
        lngID = !MasterAccountFK.Value
        If lngID > 0 Then
          strAccount = str(!AccountID) & strAccount
        End If
      Else
        lngID = 0
      End If
    Wend
    ' Leave recordset open.
    ' .Close
  End With

'  Don't terminate static objects.
'  Set rst = Nothing
'  Set tbl = Nothing
'  Set dbs = Nothing

'  Alternative expression for returning the level.
'  (Adjust vartype of return value of function.) '  RecursiveLookup = lngLevel ' As Long
  RecursiveLookup = strAccount

End Function

这假设一个表具有主键 ID 和指向父记录的外(主)键-以及具有可见键( AccountID )为0。

现在,使用这样的查询几乎可以立即很好地显示您的树,其中 Account 将是可见的复合键:

  SELECT
    *,RecursiveLookup([ID]) AS Account
  FROM
    tblAccount
  WHERE
    AccountID > 0
  ORDER BY
    RecursiveLookup([ID]);
本文链接:https://www.f2er.com/3167518.html

大家都在问