HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How to get the equivalent of array or string GROUP BY aggregate functions in Access?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
theequivalentgrouparraygetaccesshowfunctionsstringaggregate

Problem

From SQL Aggregate Functions (Office 2007) there are only these GROUP BY aggregate functions in Access SQL:

Count(), Sum(), Avg(), 
First(), Last(), Min(), Max(), 
StDev(), StDevP(), Var(), VarP()


From PostgreSQL Aggregate Functions there are (among others) also these aggregate functions in PostgreSQL:

array_agg (expression)
  -- input values, including nulls, concatenated into an array

string_agg (expression, delimiter)
  -- input values concatenated into a string, separated by delimiter


How to get the equivalent of array or string GROUP BY aggregate functions in Access?
Is it possible to build Access SQL aggregate functions?
In case it's not clear, if I this data

ID col
-----
1  A
1  B
1  C
2  A
3  A
3  B


how can I get the following aggregation?

ID cols
----------
1  A, B, C
2  A
3  A, B


Do I have to resort to VBA? Any other ideas?

I'm using Access 2007 - 2010, but if things are different in a newer version, please let me know.

Solution

Access does come with a set of domain aggregation functions. An overview of these can be found here or in the MSN documentation here. There is, unfortunately, no native domain concatenation function.

Fortunately, Patrick Matthews has published a domain concatenation function here (and reproduced below to guard against link rot) that will accomplish what you're looking for.

From the documentation of DConcat():

SELECT DConcat("Account","Sample") AS Accounts
FROM Sample
GROUP BY DConcat("Account","Sample");

Returns:
Accounts
-----------------------------------------------------------------------------
Acct1, Acct10, Acct2, Acct3, Acct4, Acct5, Acct6, Acct7, Acct8, Acct9


For the specific example in question:

SELECT ID, DConcat("col","YourTable", "ID=1") AS cols
FROM YourTable
WHERE ID=1
GROUP BY ID, DConcat("col","YourTable", "ID=1")


Should return these values:

ID cols
----------
1  A, B, C


Then repeat for each different required ID value.

`Function DConcat(ConcatColumns As String, Tbl As String, Optional Criteria As String = "", _
Optional Delimiter1 As String = ", ", Optional Delimiter2 As String = ", ", _
Optional Distinct As Boolean = True, Optional Sort As String = "Asc", _
Optional Limit As Long = 0)

' Function by Patrick G. Matthews, basically embellishing an approach seen in many
' incarnations over the years

' Requires reference to Microsoft DAO library

' This function is intended as a "domain aggregate" that concatenates (and delimits) the
' various values rather than the more usual Count, Sum, Min, Max, etc. For example:
'
' Select Field1, DConcat("Field2", "SomeTable", "[Field1] = '" & Field1 & "'") AS List
' FROM SomeTable
' GROUP BY Field1
'
' will return the distinct values of Field1, along with a concatenated list of all the
' distinct Field2 values associated with each Field1 value.

' ConcatColumns is a comma-delimited list of columns to be concatenated (typically just
' one column, but the function accommodates multiple). Place field names in square
' brackets if they do not meet the customary rules for naming DB objects
' Tbl is the table/query the data are pulled from. Place table name in square brackets
' if they do not meet the customary rules for naming DB objects
' Criteria (optional) are the criteria to be applied in the grouping. Be sure to use And
' or Or as needed to build the right logic, and to encase text values in single quotes
' and dates in #
' Delimiter1 (optional) is the delimiter used in the concatenation (default is ", ").
' Delimiter1 is applied to each row in the code query's result set
' Delimiter2 (optional) is the delimiter used in concatenating each column in the result
' set if ConcatColumns specifies more than one column (default is ", ")
' Distinct (optional) determines whether the distinct values are concatenated (True,
' default), or whether all values are concatenated (and thus may get repeated)
' Sort (optional) indicates whether the concatenated string is sorted, and if so, if it is
' Asc or Desc. Note that if ConcatColumns has >1 column and you use Desc, only the last
' column gets sorted
' Limit (optional) places a limit on how many items are placed into the concatenated string.
' The Limit argument works as a TOP N qualifier in the SELECT clause

Dim rs As DAO.Recordset
Dim SQL As String
Dim ThisItem As String
Dim FieldCounter As Long

On Error GoTo ErrHandler

' Initialize to Null

DConcat = Null

' Build up a query to grab the information needed for the concatenation

SQL = "SELECT " & IIf(Distinct, "DISTINCT ", "") & _
IIf(Limit > 0, "TOP " & Limit & " ", "") & _
ConcatColumns & " " & _
"FROM " & Tbl & " " & _
IIf(Criteria <> "", "WHERE " & Criteria & " ", "") & _
Switch(Sort = "Asc", "ORDER BY " & ConcatColumns & " Asc", _
Sort = "Desc", "ORDER BY " & ConcatColumns & " Desc", True, "")

' Open the recordset and loop through it:
' 1) Concatenate each column in each row of the recordset
' 2) Concatenate the resulting concatenated rows in the function's return value

Set rs = CurrentDb.OpenRecordset(SQL)
With rs
Do Until .EOF

' Initialize variable for this row

ThisItem = ""

' Concatenate columns on this row

For FieldCounter = 0 To rs.Fields.Count - 1
ThisItem = ThisItem & Delimiter2 & Nz(rs.Fields(FieldCounter).Value, "")
Next

' Trim leading delimiter

ThisItem = Mid(ThisItem, Len(Delimiter2) + 1)

' Concatenate row result to function return value

DConcat = Nz(DConcat, "") & Delimiter1 & ThisItem
.MoveNext
Loop
.Close
End With

' Trim leading delimiter

If Not

Code Snippets

SELECT DConcat("Account","Sample") AS Accounts
FROM Sample
GROUP BY DConcat("Account","Sample");


Returns:
Accounts
-----------------------------------------------------------------------------
Acct1, Acct10, Acct2, Acct3, Acct4, Acct5, Acct6, Acct7, Acct8, Acct9
SELECT ID, DConcat("col","YourTable", "ID=1") AS cols
FROM YourTable
WHERE ID=1
GROUP BY ID, DConcat("col","YourTable", "ID=1")
ID cols
----------
1  A, B, C

Context

StackExchange Database Administrators Q#98089, answer score: 3

Revisions (0)

No revisions yet.