1

I have designed a view in SQL Server 2008 that displays 2 columns of distinct data in this format:

Column1 Column2
A Text1
B Text2
B Text3
C Text4
D Text5
D Text6
D Text7
E Text8

What do I have to do to get the view to display only the distinct Column1 values with Column2 values concatenated like this:

Column1 Column2
A Text1
B Text2, Text3
C Text4
D Text5, Text6, Text7
E Text8

If I use the code suggested in the answers you seem to be considering as duplicate to this question, then I get this kind of result:

Column1 Column2
A Text1,Text2,Text3,Text4,Text5,Text6,Text7,Text8
B Text1,Text2,Text3,Text4,Text5,Text6,Text7,Text8
C Text1,Text2,Text3,Text4,Text5,Text6,Text7,Text8
D Text1,Text2,Text3,Text4,Text5,Text6,Text7,Text8
E Text1,Text2,Text3,Text4,Text5,Text6,Text7,Text8

Edit: The revised code from @techdo worked, many thanks.

asked Apr 10, 2013 at 4:53
3
  • 1
    What RDBMS you are using? RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, etc... Commented Apr 10, 2013 at 4:54
  • Using SQL Server 2008 Commented Apr 10, 2013 at 4:58
  • 2
    stackoverflow.com/questions/6899/… or stackoverflow.com/questions/194852/… Commented Apr 10, 2013 at 5:03

1 Answer 1

2

Please try:

SELECT
 Column1,
 STUFF(
 (SELECT ',' + Column2
 FROM YourTable t2
 WHERE t2.Column1=t1.Column1
 FOR XML PATH(''),type).value('.','nvarchar(max)'), 1, 1, '') AS Column2
FROM
 YourTable t1
GROUP BY Column1

Check LINK for more details.

answered Apr 10, 2013 at 5:03
Sign up to request clarification or add additional context in comments.

5 Comments

this code returns all column2 values for each column1 row like this: A Text1,Text2,Text3,Text4,Text5,Text6,Text7,Text8 B Text1,Text2,Text3,Text4,Text5,Text6,Text7,Text8 C Text1,Text2,Text3,Text4,Text5,Text6,Text7,Text8
Add where condition on Column1. Please check the edited answer.
I only have the ONE table.
I got it to work, thanks techdo. But it was slightly confusing using t1 and t2 since I only have 1 table.
t1 and t2 are alias names given for your table.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.