Distinct Values using STRING_AGG in SQL Server
The STRING_AGG function in SQL Server 2017 allows you to concatenate values into a single string. However, it can return duplicate values when concatenating a field with multiple occurrences.
Consider the following query:
SELECT ProjectID, STRING_AGG( newID.value, ',') WITHIN GROUP (ORDER BY newID.value) AS NewField FROM [dbo].[Data] WITH(NOLOCK) CROSS APPLY STRING_SPLIT([bID],';') AS newID WHERE newID.value IN ('O95833', 'Q96NY7-2') GROUP BY ProjectID ORDER BY ProjectID
This query returns the concatenated values, but duplicates are included:
ProjectID | NewField |
---|---|
2 | O95833,O95833,O95833,Q96NY7-2,Q96NY7-2,Q96NY7-2 |
4 | Q96NY7-2,Q96NY7-2 |
To retrieve only unique values, use the DISTINCT keyword in a subquery:
SELECT ProjectID ,STRING_AGG(value, ',') WITHIN GROUP (ORDER BY value) AS NewField FROM ( SELECT DISTINCT ProjectID , newId.value FROM [dbo].[Data] WITH (NOLOCK) CROSS APPLY STRING_SPLIT([bID],';') AS newId WHERE newId.value IN ( 'O95833' , 'Q96NY7-2' ) ) x GROUP BY ProjectID ORDER BY ProjectID
This subquery removes duplicates before applying the STRING_AGG function. The final result is:
ProjectID | NewField |
---|---|
2 | O95833, Q96NY7-2 |
4 | Q96NY7-2 |
The above is the detailed content of How to Get Distinct Values Using STRING_AGG in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!