将多行数据合并为一行

时间:2012-03-05 10:39:51

标签: sql-server-2008

表格格式如下:

ID     Category
1       a
1       b
2       a
2       b
2       c

我希望输出采用以下格式

ID              Category
1                  a,b
2                 a,b,c

请建议一种有效的方法

3 个答案:

答案 0 :(得分:0)

尝试以下查询:

 SELECT ID,  
  REPLACE(
    (SELECT  Category AS [data()] 
     FROM TableA  
     WHERE b.ID=ID
     ORDER BY Category FOR XML PATH('')),
     ' ', ', ')
FROM TableB b 
GROUP BY ID

答案 1 :(得分:0)

我上次遇到了类似的事情,我用程序解决了它。您需要在类别中为特定ID执行循环。

答案 2 :(得分:0)

也许是这样的:

测试数据

DECLARE @tbl TABLE(ID INT,Category VARCHAR(100))
INSERT INTO @tbl
VALUES
    (1,'a'),
    (1,'b'),
    (2,'a'),
    (2,'b'),
    (2,'c')

查询

;WITH CTE     ----CTE Name
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) AS RowNbr,
        ID,
        Category
    FROM
        @tbl AS tbl
)
SELECT
    CTE.ID,
    (
        STUFF
            ((
                SELECT
                    ','+Category
                FROM @tbl AS tbl
                WHERE tbl.ID=CTE.ID
                FOR XML PATH('')
                )
        ,1,1,'')
    ) AS Category
FROM
    CTE
WHERE
    CTE.RowNbr=1