【发布时间】:2015-06-03 20:49:50
【问题描述】:
我有以下临时表 (#associations):
create table #associations (ID1 nvarchar(max), ID2 nvarchar(max))
insert into #associations (ID1,ID2) values
(1,2)
,(1,3)
,(2,1)
,(2,3)
,(3,1)
,(3,2)
ID1 ID2
1 2
1 3
2 1
2 3
3 1
3 2
所有 ID 都相互关联,因此 ID1 和 ID2 中的关系偶尔会以相反的方向重复。
我需要做的是,在逗号分隔的列表中为任意数量的关系(上例中超过 3 个)选择一个完全唯一的结果集,如下所示:
ID Relationship
1 2,3
2 3
到目前为止,我有以下 SQL,但是,它并没有扁平化为唯一的关系(即我在结果中涵盖了两个方向):
select distinct
a.id1 as [ID]
,stuff(
(
select ', ' + a2.id1
from #associations a2
where a2.id2 = a.id1
for xml path('')
), 1, 1, '') as [Relationship]
from #associations a
提前感谢您的帮助。
【问题讨论】:
标签: sql sql-server sql-server-2008