第一组列CSV

时间:2013-05-02 16:58:41

标签: sql sql-server-2008

我正在尝试获取资源和相关技能,我想询问是否有将一个列中的技能分组看起来像CSV 像这样 enter image description here

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

1 个答案:

答案 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;

请参阅SQL Fiddle with Demo

您还可以将CROSS APPLYFOR 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 with Demo