Search code examples
sqlpivotcoalesce

T-SQL COALESCE does not return distinct values


This query returns duplicate values for Zip - which I don't think it should. For example: @pivotColumns returns the following list even when the sub-query for zip has a "distinct Zip". I am assuming the QUOTENAME might not be working well for the purposes of a returning a list of unique values? I want the ZipCode's with no duplicates

DECLARE   @PivotColumns AS NVARCHAR(MAX)

SELECT   @PivotColumns = COALESCE (@PivotColumns + ',','') + QUOTENAME([Zip])
FROM [dbo].[PivotStoreZip]
Where Zip in (
               Select distinct Zip 
               From PivotStoreZip 
               Where ZIP in ('39401','39402', '39406','39465','39475')
             )

print (@PivotColumns)

the print (@PivotColumns) returns the list below and, for example, [39401] repeats:

[39401],[39406],[39465],[39475],[39401],[39402],[39406],[39465],[39475]

Solution

  • You can try to use distinct in a subquery to remove duplicate Zip instead of where condition

    SELECT   @PivotColumns = COALESCE (@PivotColumns + ',','') + QUOTENAME([Zip])
    FROM (
        Select distinct Zip 
        From PivotStoreZip 
        Where ZIP in ('39401','39402', '39406','39465','39475')
    ) t1