I’d like to create a SQL Server select statement where the cross referenced data are in one column from different rows. I’d like to use stuff (if possible) and no ;with command.
Contract table
ID Subject
1 a
2 b
3 c
Company table
ID Name
1 a_ltd
2 b_ltd
3 c_ltd
4 d_ltd
5 e_ltd
ContractContractorCrossRef table (junction table)
ID ContractID_ CompanyID_
1 1 1
2 1 2
3 2 3
4 3 1
5 3 4
6 3 5
I’d like this result:
Contract.ID company.Name
1 a_ltd, b_ltd
2 c_ltd
3 a_ltd, d_ltd, e_ltd
Populate data:
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:
select #Contract.ID, #Company.Name from #Contract
inner join #ccRef on #Contract.ID = #ccRef.ContractID_ inner join #Company
on #ccRef.CompanyID_ = #Company.ID
Select result: (not wanted)
ID Name
1 a_ltd
1 b_ltd
2 c_ltd
3 a_ltd
3 d_ltd
3 e_ltd
Requested result:
Contract.ID company.Name
1 a_ltd, b_ltd
2 c_ltd
3 a_ltd, d_ltd, e_ltd
Try this. I have not tested the code as i do not have ddl for these tables.But it should work..