stighy
stighy

Reputation: 7170

Sql Query: how to solve this query issue?

i've this two tables:

Table 1

Key, CenterId, Value

01 Center A 10

02 Center B 100

03 Center C 50

and

Table 2

Center,  SubCenter, A-Field,  B-Field
Center A   Sub 1      ...     ...
Center A   Sub 2
Center A   Sub 3      ...     ...

I need to get ONE ROW per Center (one row from Table 1) and, all the subcenters but without duplicating row ... so my last result must be:

Query Result

 Center,  Value, List-of-SubCenter
 Center A,  10,   Sub1 Sub2 Sub 3
 Center B, 100,   Sub4 ...  Sub N

How to do this in Sql (in particular SQL-SERVER) ?

Thank you

Upvotes: 2

Views: 79

Answers (1)

PHeiberg
PHeiberg

Reputation: 29851

This should work for SQL Server 2005 and upwards

SELECT t1.centerid, t1.value, LEFT(el.sublist, LEN(el.sublist)-1) AS subcenters 
FROM Table1 t1
CROSS APPLY (SELECT t2.subcenter + ',' AS [text()]
             FROM Table2 t2
             WHERE t2.center = t1.centerid 
             FOR XML PATH(''))el(sublist)

Upvotes: 1

Related Questions