1

I have a table with below data.

columnA columnB
ONE value 1
ONE value 2
ONE value 3
TWO value 1
TWO value 2
THREE value 1

Need help in creating a query which gives below

COLUMN X COLUMN Y
ONE value 1, value 2, value 3
TWO value 1, value 2
THREE value 1
Kin Shah
62.6k6 gold badges124 silver badges247 bronze badges
asked Jun 27, 2018 at 20:44
2
  • To get help writing a query, check out this Q&A. Commented Jun 27, 2018 at 20:49
  • 1
    Also, please specify your version of SQL Server, as the options are different for different versions. Commented Jun 27, 2018 at 22:16

1 Answer 1

6

What you are needing help is called Grouped Concatenation in SQL Server

This sql fiddle that I created will help you.

Basically you use stuff + FOR XML PATH.

If you are on sql server 2017 (vNEXT) then STRING_AGG is an inbuilt function that you can use

-- sql server vNEXT

SELECT [ColumnA] = [ColumnA],
 [ColumnBs] = STRING_AGG(ColumnB, ',')
 from dbo.Table1 
 group by ColumnA
answered Jun 27, 2018 at 20:54
1
  • Case when row_number() over (order by columnb) = 1 then '' else ',' end + columnB is more understandable than stuff. Or use lag/lead if you want to do different things for the first and last. Commented Jun 28, 2018 at 0:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.