0

我正在尝试获取资源和辅助技能我想问是否有办法将技能分组在一个列中看起来像 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
4

1 回答 1

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;

请参阅SQL Fiddle with Demo

您还可以使用CROSS APPLYwith 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);

请参阅带有演示的 SQL Fiddle

于 2013-05-02T17:12:07.563 回答