Skip to content
Advertisement

sql – select partially unique values and concatenate non unique values into string

Say I have the following data set:

How can I group by columns A and B and return a third column that is all unique values of C for that group concatenated together (in a comma separated string) using SQL.

For clarity this is the resultant data set I am looking for:

I am currently querying this in MS access, but ideally would be nice if there would be a common solution for all SQL databases.

Note: In this use case the column C only has 10 known values being 0-9

Advertisement

Answer

So using the ConcatRelated function did not really solve my problem as it appeared to be quite inefficient and caused the already slow MS access (with a large dataset) to grind to a halt.

I was able to do this in SQL using some sub queries for my use case – As added/noted above the column C consists on a well defined data set.

For my use case the following SQL (and concatenation) in MS Access worked:

Other alternatives I looked at was exporting all data/tables into another database that supported string aggregation. This would provide a much more universal solution where the contents of the C column were not known. I believe the solutions here would be (please feel free to expand this list if it helps):

Mariadb: Use group_concat

Oracle 11g R2 and above: Use listagg

Oracle below 11g R2: Use wm_concat

Hopefully this helps someone…

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement