STRING_AGG with distinct values
I'm currently using STRING_AGG to display a list of barcodes per SKU. Unfortunately, our database includes duplicate barcodes, and the result displays all of them. For example, "1234, 5678, 1234, 5678."
I understand that I can use SELECT DISTINCT to only display unique barcode values, but I'm not sure how to implement DISTINCT in only one column. Is there a way to resolve this or a better way to go about this issue?
Our current code, simplified, looks as below:
SELECT StoreCode, SKU, STRING_AGG(Barcode, ', '), FROM ItemSummaryView WHERE SKU = @SKU GROUP BY StoreCode, SKU ORDER BY StoreCode, SKU
This discussion has been closed.
Comments
Hello!
In T-SQL, the STRING_AGG function does not support the DISTINCT modifier within its arguments, so barcodes must be deduplicated beforehand either in a subquery or CTE at the SQL level, or on the report side:
If the SQL query cannot be modified, you can collect unique barcodes in a `HashSet<string>` (in the report script as you iterate through the rows of the group) and output `string.Join(“, ”, hashSet)` in the group footer.