0

How do i fetch the details of following table

table1:

c1    c2    
ta     a    
tb     c    
ta     b    
tb     d    

by grouping with same name, like

ta    a,b
tb    c,d

which function to use in mssql

2
  • 1
    If 2017+ you are looking for string_agg() otherwise the XML approaches presented. Commented Feb 6, 2020 at 14:45
  • Which SQL Server version? Commented Feb 6, 2020 at 14:45

3 Answers 3

3

You can use XML stuff combination

select distinct c1,
STUFF((Select ','+c2    
from table1 T1
where T1.c1 =T2.c1    
FOR XML PATH('')),1,1,'') from table1 T2
Sign up to request clarification or add additional context in comments.

1 Comment

All the answers are correct, but i found this one very easy :p
2

Depends on your version of SQL Server; as of SQL 2017 you can use

Table

DECLARE @t TABLE (C1 VARCHAR(255), C2 VARCHAR(25))
INSERT INTO @t VALUES 
('ta','a'),('tb','c'),('ta','b'),('tb','d')

Query

SELECT C1, STRING_AGG(C2,',')
FROM    @t
GROUP BY C1

Comments

2

Im late to the party but here ya go:

In 2017 string concatenation becomes super easy.

In older forms of SQL Server, you could use multiple techniques to get it done, like FOR XML (as show by another user), Unions, loops (which while gross is technically another way to do so) and of course the dark arts of recursive CTE's (which might be over kill for this example).

drop table #tmp;
create table #tmp
    (
        c1 varchar(2)
        , c2 varchar (2)
    );

INSERT INTO #tmp (c1, c2) VALUES
    ('ta', 'a'),
    ('tb', 'c'),
    ('ta', 'b'),
    ('tb', 'd');


SELECT c1, STRING_AGG(c2, ',') AS Concat
FROM #tmp
GROUP BY C1;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.