SQL多行到一个CSV

时间:2014-01-31 17:44:46

标签: sql sql-server sql-server-2008 tsql

我在使用CSV

将多行连接转换为一行时遇到问题

这就是我所拥有的

   [Project Number] | [Resources]
1   25254              , Jim Anderson
2   25254              , Becky Smith
3   32564              , Amy Dickerson
4   32564              , James Walsh
5   25679              , Jim Anderson
6   25679              , James Walsh

这就是我需要的

   [Project Number] | [Resources]
1   25254              Jim Anderson, Becky Smith
2   32564              Amy Dickerson, James Walsh
3   25679              Jim Anderson, James Walsh

这是我正在使用的查询

select *
from(
        select
            'Project Number' = p.ProjectID
        ,   'Resources' = ', ' + pe.Name
        from
            Projects p (nolock)
        left join Persons pe (nolock) on p.PersonsID = pe.PersonsID
        where
            year( p.CreatedDTM) = 2013
            and p.TypeID = 1
    ) ta
order by ta.APAID

请帮忙。

谢谢。

1 个答案:

答案 0 :(得分:0)

select [Project Number],
    stuff((select ',' + CAST(t2.Resources as varchar(10))
     from t t2 where t1.[Project Number]= t2.[Project Number]
     for xml path('')),1,1,'') Resources
from t t1
group by [Project Number]

<强>输出:

| PROJECT NUMBER |            Resources |
|----------------|-----------------------|
|          25254 | Jim Anders,Becky Smit |
|          25679 | Jim Anders,James Wals |
|          32564 | Amy Dicker,James Wals |

<强> SQL FIDDLE