0

I have data like this:

  • Person A has a relationship with Person B, and person A has a relationship with Person C
  • Person B has a relationship with D and E.

enter image description here

I want to view result in group in SQL Server (A, B ,C,...) and (B,D,E,...)

enter image description here

I have tried looking recursive but not getting this to implement.

I need to do this in SQL.

Thanks for the help .

1 Answer 1

2

you can achieve without using recursive cte. Try the following using string_agg and concat. here is the demo.

select
  concat(columnA, ', ', string_agg(columnB, ', ')) as columnC
from myTable
group by
  columnA

output:

|columnC|
*-------*
|A, B, C|
|B, D, E|

In SQL Server 2012 you can use XML PATH as following

select
  concat(
  columnA, ',',
  stuff((
            select ', ' + columnB
            from myTable m1
            where m1.columnA = m2.columnA
            for xml path('')
        ), 1, 1, ''
    )) as columnC
from myTable m2
group by
  columnA
Sign up to request clarification or add additional context in comments.

2 Comments

tks your help. Can you help me replace string_agg in sql server 2012 or 2008?
tks for your help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.