Home > Software design >  Return all the distinct values of Product Column using T-SQL all values should be Distinct
Return all the distinct values of Product Column using T-SQL all values should be Distinct

Time:03-18

Take the following table:

ID Products
12 xx,yy,xx
13 yy,xx,yy
14 tt,xx,tt
15 yy,yy,yy

I need a T-SQL to give me distinct Values in the Products Column

Required Result as below:

ID Products
12 xx,yy
13 yy,xx
14 tt,xx
15 yy

CodePudding user response:

use STRING_SPLIT,distinct and string_agg as follows

SELECT ID,
       String_agg(value, ',') AS Products
FROM   (SELECT DISTINCT ID,
                        value
        FROM   (SELECT ID,
                       a.value
                FROM   table
                       CROSS apply String_split(products, ',') a) b) c
GROUP  BY ID
  • Related