我正在尝试获取资源和相关技能,我想询问是否有将一个列中的技能分组看起来像CSV 像这样
ID技能
1,阅读,写作
2,编程,阅读
SELECT Resources.Id, Skills.Description
FROM Resources INNER JOIN
Skills_Resources ON Resources.Id = Skills_Resources.ResourceID INNER JOIN
Skills ON Skills_Resources.skillID = Skills.Id
答案 0 :(得分:0)
为了将多行连接在一起,您需要使用FOR XML PATH
:
SELECT distinct r.Id,
STUFF(
(SELECT ', ' + cast(s.description as varchar(50))
FROM Skills s
INNER JOIN Skills_Resources sr
ON sr.skillID = s.Id
where r.Id = sr.ResourceID
FOR XML PATH (''))
, 1, 1, '') AS skills
FROM Resources r;
您还可以将CROSS APPLY
与FOR XML PATH
:
select distinct r.Id,
left(s.skill, len(s.skill)-1) skills
from Resources r
cross apply
(
select s.description + ', '
FROM Skills s
INNER JOIN Skills_Resources sr
ON sr.skillID = s.Id
where r.Id = sr.ResourceID
FOR XML PATH('')
) s (skill);