【问题标题】:MSSQL 2008: Get unique values from a many-to-many tableMSSQL 2008:从多对多表中获取唯一值
【发布时间】: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


    【解决方案1】:

    您可以像 AND a.id1 > a2.id1 这样在您的共同相关查询中添加额外的检查

    select distinct
        a.id1 as [ID] 
        ,stuff(
        (
            select ', ' + a2.id1 
            from #associations a2
            where a2.id2 = a.id1  
            AND a.id1  > a2.id1  
            for xml path('')
        ), 1, 1, '') as [Relationship]
        from #associations a
    

    这将限制重复关系。

    在这样的关系查询之前,您可能还必须执行 UNION#associations

    SELECT ID1, ID2 FROM #associations
    UNION 
    SELECT ID2 AS ID1, ID1 as ID2 FROM #associations
    

    并在您的查询中使用它而不是 #associations

    【讨论】:

      【解决方案2】:

      试试这个:

      ;with a as (
      select distinct case when a.ID1 < a.ID2 then a.ID1 else a.ID2 end ID1
          , case when a.ID1 < a.ID2 then a.ID2 else a.ID1 end ID2
      from #associations a
      )
      select distinct a.ID1 as [ID]
          , STUFF((select ', '+a2.ID2 from a a2 where a.ID1 = a2.ID1 for xml path('')),1,2,'') as [Relationship]
      from a
      

      如果ID1小于ID2,则使用ID1作为第一个id,ID2作为第二个id,否则交换ID1和ID2。

      【讨论】:

        猜你喜欢
        • 2015-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-22
        相关资源
        最近更新 更多