需要帮助基于GROUP BY将多行分组为单个字符串?

时间:2016-10-05 18:54:53

标签: sql-server xml tsql sql-server-2005 group-by

之前可能已经提出过这个问题,但是我一直在进行一些挖掘,而且找不到任何类似的东西。提前致谢

编辑:完全忘了。我们正在使用SQL 2005(否则我可能只使用GROUP_CONCAT)

样本表:

ID  CATEGORY    ATTRIBUTE
1   A   Piano
1   A   Saxophone
1   B   Jazz
1   C   Mellow
1   C   Pensive
2   A   Drums
2   A   Guitar
2   B   Rock
2   B   Classics
2   C   Upbeat
2   C   High Energy

期望的输出:

ID  CATEGORY    ATTRIBUTE
1   A   Piano, Saxophone
1   B   Jazz
1   C   Mellow, Pensive
2   A   Drums, Guitar
2   B   Rock, Classics
2   C   Upbeat, High Energy

4 个答案:

答案 0 :(得分:1)

使用GROUP_CONCAT()

fly sync

答案 1 :(得分:1)

尝试这一个

SELECT ID,
        CATEGORY,
        ATTRIBUTE1
 FROM TABLENAME TB
 cross apply 
   (SELECT TB1.ATTRIBUTE + ', '
    FROM TABLENAME TB1
    WHERE TB1.ID = TB.ID  For XML PATH(''))A1 (ATTRIBUTE1)
GROUP BY TB.ID,TB.CATEGORY

答案 2 :(得分:0)

FOR MS SQL使用此语法

SELECT table_name, LEFT(column_names , LEN(column_names )-1) AS column_names
FROM information_schema.columns AS extern
CROSS APPLY
(
    SELECT column_name + ','
    FROM information_schema.columns AS intern
    WHERE extern.table_name = intern.table_name
    FOR XML PATH('')
) pre_trimmed (column_names)
GROUP BY table_name, column_names;

答案 3 :(得分:0)

使用XML PATH只是标准的旧式嵌套查询应该适用于SQL 2005。

DECLARE @TableName TABLE
(
     ID         INT
    ,CATEGORY   NVARCHAR(5)
    ,ATTRIBUTE  NVARCHAR(50)
    ,PRIMARY KEY(ID, CATEGORY, ATTRIBUTE)
)

INSERT INTO @TableName
(
     ID         
    ,CATEGORY
    ,ATTRIBUTE
)
VALUES
    (1   ,'A'   ,'Piano'            ),
    (1   ,'A'   ,'Saxophone'        ),
    (1   ,'B'   ,'Jazz'             ),
    (1   ,'C'   ,'Mellow'           ),
    (1   ,'C'   ,'Pensive'          ),
    (2   ,'A'   ,'Drums'            ),
    (2   ,'A'   ,'Guitar'           ),
    (2   ,'B'   ,'Rock'             ),
    (2   ,'B'   ,'Classics'         ),
    (2   ,'C'   ,'Upbeat'           ),
    (2   ,'C'   ,'High Energy'      );


WITH CTE_Concatenate 
AS
(
    SELECT  ID
            ,CATEGORY
            ,(
                SELECT ATTRIBUTE + ','
                FROM @TableName [Inner]
                WHERE [Outer].ID = [Inner].ID AND [Outer].CATEGORY = [Inner].CATEGORY
                FOR XML PATH('')
             ) AS ATTRIBUTES
    FROM    @TableName [Outer]
    GROUP BY    ID, CATEGORY
)
SELECT  ID
        ,CATEGORY
        ,LEFT(ATTRIBUTES, LEN(ATTRIBUTES) - 1) AS ATTRIBUTES
FROM    CTE_Concatenate;

可以使用STUFF函数进一步简化查询,如下所示:

SELECT  ID
        ,CATEGORY
        ,STUFF( (
            SELECT ',' + ATTRIBUTE 
            FROM @TableName [Inner]
            WHERE [Outer].ID = [Inner].ID AND [Outer].CATEGORY = [Inner].CATEGORY
            FOR XML PATH('') ), 1, 1, '') AS ATTRIBUTES
FROM    @TableName [Outer]
GROUP BY    ID, CATEGORY;