uniquedistinctsql-server-2014for-xml-pathstring-aggregation

Unique values concatenate with a comma separated value in SQL Server 2014 per ID


I have two tables in SQL Server 2014:

  1. current_entry
  2. data_by_client

I have two columns User_ and Skill. I need unique Skill values to concatenate from both the tables in the select statement as per the User Ids. String_Agg doesn't work in SQL Server 2014, so I tried using XML PATH.

Please find the attached screenshot for the expected output :

enter image description here

Here is the SQL Fiddle for it : SQL Fiddle

I have used the below XML PATH query :

SELECT 
    User_, Products + Skill 
FROM
    (SELECT DISTINCT 
         User_, Skill,
         (SELECT DISTINCT rs.Skill + ','
          FROM dbo.current_entry u 
          INNER JOIN dbo.data_by_client rs ON u.User_ = rs.User_
          WHERE rs.User_ = r.User_
          FOR XML PATH('')) AS Products
     FROM    
         dbo.current_entry r) l

I am facing issues as I am not getting the expected output.


Solution

  • Can you try to workout your solution using the following approach:

    SELECT
       t1.user,
       Item = stuff((SELECT ( ', ' + skill )
                           FROM #string_test t2
                          WHERE t1.user = t2.user
                          ORDER BY 1
                            FOR XML PATH( '' )
                        ), 1, 1, '' )FROM #string_test t1
    GROUP BY user
    

    Reference: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/4ac19fe5-be05-479f-bcc2-8fdfa6c1ae1f/pivot-string-concatenation?forum=transactsql

    You can then use a custom SQL function to remove duplicates. Refer to http://blog.sqlauthority.com/2009/01/15/sql-server-remove-duplicate-entry-from-comma-delimited-string-udf/amp/