0

我想创建一个 SQL Serverselect语句,其中交叉引用的数据位于不同行的一列中。我想使用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
4

2 回答 2

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

于 2012-07-26T15:34:19.210 回答
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)
于 2012-07-26T15:49:58.737 回答