合并交叉引用表中的行

时间:2012-07-26 15:10:54

标签: sql-server merge rows junction-table

我想创建一个SQL Server select语句,其中交叉引用的数据位于不同行的一列中。我想使用stuff(如果可能)而不是;with命令。

合同

ID  Subject
1   a
2   b
3   c

公司

ID  Name
1   a_ltd
2   b_ltd
3   c_ltd
4   d_ltd
5   e_ltd

ContractContractorCrossRef 表(联结表)

ID  ContractID_ CompanyID_
1   1               1
2   1               2
3   2               3
4   3               1
5   3               4
6   3               5

我想要这个结果:

Contract.ID company.Name
1           a_ltd, b_ltd
2           c_ltd
3           a_ltd, d_ltd, e_ltd

填充数据:

create table #Contract (ID INT, Subject VARCHAR(1))
INSERT  #Contract
SELECT  1, 'a' UNION ALL
SELECT  2, 'b' UNION ALL
SELECT  3, 'c'

create table #Company (ID INT, Name VARCHAR(5))
INSERT  #Company
SELECT  1, 'a_ltd' UNION ALL
SELECT  2, 'b_ltd' UNION ALL
SELECT  3, 'c_ltd' UNION ALL
SELECT  4, 'd_ltd' UNION ALL
SELECT  5, 'e_ltd'

create table #ccRef (ID INT, ContractID_ INT, CompanyID_ INT)
INSERT  #ccRef
SELECT  1, 1, 1 UNION ALL
SELECT  2, 1, 2 UNION ALL
SELECT  3, 2, 3 UNION ALL
SELECT  4, 3, 1 UNION ALL
SELECT  5, 3, 4 UNION ALL
SELECT  6, 3, 5 

:选择:

select #Contract.ID, #Company.Name from #Contract
inner join #ccRef on #Contract.ID = #ccRef.ContractID_ inner join #Company
on #ccRef.CompanyID_ = #Company.ID

选择结果:(不想要)

ID  Name
1   a_ltd
1   b_ltd
2   c_ltd
3   a_ltd
3   d_ltd
3   e_ltd

请求结果:

Contract.ID company.Name
1           a_ltd, b_ltd
2           c_ltd
3           a_ltd, d_ltd, e_ltd

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

SELECT x.id
  , left(CompanyName, len(CompanyName)-1) as CompanyName
FROM
(
  SELECT DISTINCT ct.id
    , (SELECT CAST(co.Name + ', ' AS VARCHAR(MAX)) 
           FROM contractcompanycrossref cc
           LEFT JOIN company co
            on cc.companyid = co.id
           WHERE (cc.contractid = ct.id) 
           FOR XML PATH ('')
        ) AS CompanyName
  from contract ct
  left join contractcompanycrossref cc
    on ct.id = cc.contractid
) x

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

试试这个。我没有测试代码,因为我没有这些表的ddl。但它应该工作..

       SELECT ct.id ,
 left(companyname.value('.','varchar(max)'), len(companyname.value('.','varchar(max)'))-1) as companyname 
from 
    contract ct 
    cross apply 
    ( 
    select cm.name + ',' [text()]
    from 
    contractcompanycrossref cc 

    inner join company cm
    on cc.companyid = cm.ID
      where ct.id = cc.contractid 
    for xml path (''),type
    ) cmnames(companyname)