我有5张桌子- 定义-
ID | defName |
--------------
1 | def1 |
2 | def2 |
3 | def3 |
4 | def4 |
def_treat_relations
defID | treatID|
---------------
3 | 5 |
3 | 2 |
2 | 3 |
4 | 3 |
def_specialty_relations
defID | specID |
----------------
3 | 2 |
3 | 3 |
2 | 4 |
4 | 1 |
特色
ID | specName |
---------------
1 | spec1 |
2 | spec2 |
3 | spec3 |
4 | spec4 |
苦恼
ID | treatName |
----------------
1 | treat1 |
2 | treat2 |
3 | treat3 |
4 | treat4 |
我需要一个查询,向我显示所有定义以及一系列处理方法和特色
结果应如下所示:
defname | speces | treat |
-------------------------------
def1 | | |
def2 |spec4 |treat3 |
def3 |spec2,spec3|treat5,treat2|
def4 |spec1 |treat3 |
我尝试了一些尝试,但遇到了麻烦...在此先感谢
答案 0 :(得分:2)
您需要使用某种字符串聚合来实现此目的。较新版本的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 |
+---------+--------------+----------------+