1

I need a TSQL version of group_concat Simmilar to the example found here:

Policy   Destination   ID
-------------------------
PolA     DestA         1    
PolA     DestA         2    
PolB     DestB         3     
PolB     DestB         4    
PolC     DestC         5
PolC     DestC         6
PolC     DestD         7   

The output should look like this:

PolA   DestA   1,2
PolB   DestB   3,4
PolC   DestC   5,6
PolC   DestD   7

The grouping is on the uniqueness of both the first 2 columns, and then a concatenated output on the third.

I found this link but it only take into account 2 columns

Any help would be appreciated.

5
  • Possible duplicate of Simulating group_concat MySQL function in Microsoft SQL Server 2005? Commented Oct 18, 2017 at 17:26
  • 1
    Please tag which dbms you are using. If this is SQL Server, add the tag. Also, tag which SQL Server you are using. STRING_AGG may not exist in earlier version. Secondly, what have you tried so far? Commented Oct 18, 2017 at 17:37
  • As he wrote TSQL in the question, we can assume the DBMS as SQL Server and i suggested that edit already. @user5947977 - Did you try my answer? Commented Oct 18, 2017 at 17:44
  • @user5947977 - Please mark the answer as useful(upvote) also as it worked for your issue. Commented Oct 19, 2017 at 7:28
  • thank you all, noted for future, the answer below worked a treat :) Commented Oct 19, 2017 at 7:29

3 Answers 3

1

You can try this :

SELECT G.Policy, G.Destination,
    stuff(
    (select cast(',' as varchar(max)) + U.ID
    from yourtable U
    WHERE U.Policy = G.Policy and U.Destination = G.Destination
    order by U.Policy
    for xml path('')
    ), 1, 1, '') AS IDs
FROM yourtable G group BY G.Policy, G.Destination
Sign up to request clarification or add additional context in comments.

Comments

1

In MSSQL Synax:

SELECT Policy, Destination, STRING_AGG ( [ID], ',' ) IDs
FROM Table

1 Comment

This method assumes you using SQL Server 2017
0

I just create the PolA example table for you, just replace the CTE as your table, try below:

WITH ABC
as
(
select   'PolA' as Policy,'DestA' as Destination,'1' as ID  
UNION ALL 
select 'PolA','DestA','2'
)

SELECT Policy, Destination,
 STUFF((SELECT ',' + A.ID FROM ABC as A WHERE A.Policy = B.Policy FOR XML PATH('')),1,1,'') as ID
FROM ABC as B
GROUP BY B.policy, B.Destination

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.