使用Groupby另一列将表行输出为XML

时间:2014-04-23 06:30:44

标签: sql sql-server xml

我有下表:

Dept     Skills
1        200
1        250
2        150
2        200
2        250

并要求此输出:

Dept      XMLcolumn
1         <xcol>200></xcol><xcol>250</xcol>
2         <xcol>150></xcol><xcol>200</xcol><xcol>250</xcol>

我尝试了FOR XML PATH但没有取得多大成功:

select dept, skills from table for xml path('xcol'), type

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

请尝试:

SELECT Dept,
    (SELECT '<xcol>' + CAST(Skills as nvarchar)+ '</xcol>'
       FROM tbl a
       where a.Dept=b.Dept
        FOR XML PATH(''),type).value('.','nvarchar(max)') XMLColumn
FROM tbl b
group by Dept

答案 1 :(得分:2)

这样的东西
DECLARE @TABLE TABLE(
        Dept INT,
        Skills INT
)

INSERT INTO @TABLE VALUES ( 1,200),( 1,250),( 2,150),( 2,200),( 2,250)

SELECT  Dept,
        (
            SELECT  Skills xcol
            FROM    @TABLE
            WHERE   Dept = t.Dept
            FOR XML RAW(''), ELEMENTS
        )
FROM    @TABLE t
GROUP BY    Dept

SQL Fiddle DEMO