Concatenate Rows in Microsoft Access

孤街浪徒 提交于 2019-11-29 16:50:39

Create a module and add the following code:

Function liststuff(company)

    Dim curr As Database
    Dim rs As Recordset
    Dim SQLCmd As String
    Dim productList As String

    Set curr = CurrentDb()

    SQLCmd = "SELECT Product FROM table1 WHERE [Company Name] = """ & company & """"

    Set rs = curr.OpenRecordset(SQLCmd)

    If Not rs.EOF Then
        rs.MoveFirst
    End If

    Do While Not rs.EOF
        productList = productList & rs(0) & ", "
        rs.MoveNext
    Loop

    liststuff = productList

End Function

You may need to change the database values to your actual table name and field names.

In your query use:

SELECT Table1.[Company Name], Table1.Address, Liststuff([Company Name]) AS [List of Products]
FROM Table1
GROUP BY Table1.[Company Name], Table1.Address;

"The only thing I can think of is that the size of my table (~290,000 rows) could be making it too slow, but I've run different queries on the table without an issue."

ConcatRelated() imposes a much greater workload on the db engine than your other queries. Essentially the engine must run a separate query to gather and concatenate the related values for each row of the result set.

If you suspect 290K rows is the source of the problem, design and test your query using a small sample table as its data source. Once you get the query working with that small table, switch its data source to the big table.

However I suspect you have another issue. Notice Mr. Browne wrote that function to accept a third parameter, strWhere, and you're giving the function only 2 parameters. It seems you're asking ConcatRelated() to concatenate all the Product field values from the Addresses table ... and do that concatenation again for every row in the result set. I don't believe that's what you actually want.

Go to the Immediate window (Ctrl+g), and test an expression to give you what you want for a single company. As a wild guess, perhaps you need something like this ...

? ConcatRelated("Product","Addresses", "[Company Name]='Company A'")

Once you figure out a suitable ConcatRelated expression, adapt your query to use it by passing in the current [Company Name] value.

Note that if your strWhere parameter includes a condition based on the [Company Name] field, that field should be indexed so the db engine need not perform a full table scan to find the matching rows.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!