Вам нужно использовать какой-либо тип агрегирования строк для достижения этой цели.Более новые версии SQL Server имеют string_agg
, который может сделать это за вас, но, поскольку вы не указали версию, здесь есть решение, использующее for xml
, а stuff
более обратно совместимо:
declare @definition table(ID int, defName varchar(10));
insert into @definition values(1,'def1'),(2,'def2'),(3,'def3'),(4,'def4');
declare @def_treat_relations table(ID int, treatID int);
insert into @def_treat_relations values (3,5),(3,2),(2,3),(4,3);
declare @def_specialty_relations table(ID int, specID int);
insert into @def_specialty_relations values (3,2),(3,3),(2,4),(4,1);
declare @specialty table(ID int, specName varchar(10));
insert into @specialty values (1,'spec1'),(2,'spec2'),(3,'spec3'),(4,'spec4');
declare @tretments table(ID int, treatName varchar(10));
insert into @tretments values (1,'treat1'),(2,'treat2'),(3,'treat3'),(4,'treat4'),(5,'treat5');
select d.defName
,isnull(
stuff((select ', ' + s.specName
from @def_specialty_relations as sr
left join @specialty as s
on sr.specID = s.ID
where d.ID = sr.ID
order by s.specName
for xml path('')
)
,1,2,'')
,'')
as specs
,isnull(
stuff((select ', ' + t.treatName
from @def_treat_relations as tr
left join @tretments as t
on tr.treatID = t.ID
where d.ID = tr.ID
order by t.treatName
for xml path('')
)
,1,2,'')
,'')
as treat
from @definition as d
left join @def_treat_relations as tr
on d.ID = tr.ID
left join @tretments as t
on tr.treatID = t.ID
order by d.defName;
Вывод
+---------+--------------+----------------+
| defName | specs | treat |
+---------+--------------+----------------+
| def1 | | |
| def2 | spec4 | treat3 |
| def3 | spec2, spec3 | treat2, treat5 |
| def3 | spec2, spec3 | treat2, treat5 |
| def4 | spec1 | treat3 |
+---------+--------------+----------------+