Skip to content
Advertisement

Get unique values using STRING_AGG in SQL Server

The following query returns the results shown below:

Results:

Using the newly added STRING_AGG function (in SQL Server 2017) as it is shown in the following query I am able to get the result-set below.

Results:

I would like my final output to have only unique elements as below:

Any suggestions about how to get this result? Please feel free to refine/redesign from scratch my query if needed.

Advertisement

Answer

Use the DISTINCT keyword in a subquery to remove duplicates before combining the results: SQL Fiddle

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