How to use GROUP BY to concatenate strings in SQL Server?

前端 未结 20 2528
无人及你
无人及你 2020-11-21 04:33

How do I get:

id       Name       Value
1          A          4
1          B          8
2          C          9

to

id               


        
20条回答
  •  借酒劲吻你
    2020-11-21 05:05

    Install the SQLCLR Aggregates from http://groupconcat.codeplex.com

    Then you can write code like this to get the result you asked for:

    CREATE TABLE foo
    (
     id INT,
     name CHAR(1),
     Value CHAR(1)
    );
    
    INSERT  INTO dbo.foo
        (id, name, Value)
    VALUES  (1, 'A', '4'),
            (1, 'B', '8'),
            (2, 'C', '9');
    
    SELECT  id,
        dbo.GROUP_CONCAT(name + ':' + Value) AS [Column]
    FROM    dbo.foo
    GROUP BY id;
    

提交回复
热议问题