我想创建一个 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