Help with TSQL join query
Based on below 2 tables
declare @开发者_开发技巧t1 table
(
Id int,
Title varchar(100),
RelatedId int
)
insert into @t1 values(1,'A',2)
insert into @t1 values(1,'A',3)
declare @t2 table
(
Id int,
Title varchar(100)
)
insert into @t2 values
(2,'B'),
(3,'C')
I am trying to get the below output
Id Title RelatedItems
---------------------------------
1 A 2 (B), 3 (C)
I tried the following:
select t1.Id,t1.Title, cast(t2.Id as varchar) + ' (' + t2.Title + ')' from @t1 as t1
left outer join @t2 as t2
on t1.RelatedId=t2.Id
But that gives 2 different rows. I want just one row with the data combined in the third column (as shown above). Pls. suggest.
Use:
SELECT DISTINCT
b.id,
b.title,
STUFF((SELECT ','+ CAST(t2.id AS VARCHAR(100)) + ' ('+ t2.title +')'
FROM t2
JOIN t1 a ON a.relatedid = t2.id
WHERE a.id = b.id
FOR XML PATH('')), 1, 1, '')
FROM t1 b
精彩评论