帮助TSQL连接查询

时间:2010-09-13 23:58:14

标签: sql sql-server tsql sql-server-2008

基于以下2个表格

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')

我想获得以下输出

Id    Title     RelatedItems 
---------------------------------
1     A         2 (B), 3 (C)

我尝试了以下内容:

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

但是这会产生2个不同的行。我只想在第三列中合并一行数据(如上所示)。 PLS。建议。

1 个答案:

答案 0 :(得分:3)

使用:

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