在Access中连接记录和GROUP BY

时间:2013-03-25 21:11:17

标签: sql ms-access concatenation

我有一张这样的表:

title               part                   desc
Blah This           1                      This begins the
Blah This           2                      example table.
Some Record         1                      Hello
Another             1                      This text extends a bit
Another             2                      further so it is in
Another             3                      another record in the
Another             4                      table

在Access中,我希望为GROUP BY title构建一个查询/ SQL并连接desc字段,使其如下所示:

title              desc
Blah This          This begins the example table.
Some Record        Hello
Another            This text extends a bit further so it is in another record in the table

如何只用SQL(没有VBA /脚本)来完成? FOR XML PATH似乎在Access中不起作用,只在SQL Server中起作用。我在这里尝试了VBA How to improve efficiency of this query & VBA?,但它太慢了。

或者是否有一个可以使用的函数在查询已经打开时不会连续运行?

2 个答案:

答案 0 :(得分:5)

Access中没有Group_Concat:/。可能没有解除VBA的解决方案 这是一个可能的:Concatenating Rows through a query

答案 1 :(得分:1)

以下是使用VBA解决此问题的粗略概述;通过对详细记录运行单个数据库查询,它的执行速度更快:

Set rsParent = CodeDb.OpenRecordset("SELECT * FROM MainTable ORDER BY HeaderID")
Set rsDetail = CodeDb.OpenRecordset("SELECT * FROM DetailTable ORDER BY HeaderID")
Do Until rsParent.EOF
  ...
  myString = rsParent!MainHeaderName & AggregateDetails(rsDetail, rsParent!HeaderID)
  rsParent.MoveNext
Loop
...

Function AggregateDetails(rsDetail as Recordset, HeaderID as String) as String
   Dim DetailString as String

   Do While rsDetail!HeaderID = HeaderID
      DetailString = DetailString & ", " & rsDetail!DetailName
      rsDetail.MoveNext
      If rsDetail.EOF Then Exit Do
   Loop
   AggregateDetails = DetailString
End Function