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

前端 未结 20 2535
无人及你
无人及你 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 04:46

    Another example without the garbage: ",TYPE).value('(./text())[1]','VARCHAR(MAX)')"

    WITH t AS (
        SELECT 1 n, 1 g, 1 v
        UNION ALL 
        SELECT 2 n, 1 g, 2 v
        UNION ALL 
        SELECT 3 n, 2 g, 3 v
    )
    SELECT g
            , STUFF (
                    (
                        SELECT ', ' + CAST(v AS VARCHAR(MAX))
                        FROM t sub_t
                        WHERE sub_t.g = main_t.g
                        FOR XML PATH('')
                    )
                    , 1, 2, ''
            ) cg
    FROM t main_t
    GROUP BY g
    

    Input-output is

    *************************   ->  *********************
    *   n   *   g   *   v   *       *   g   *   cg      *
    *   -   *   -   *   -   *       *   -   *   -       *
    *   1   *   1   *   1   *       *   1   *   1, 2    *
    *   2   *   1   *   2   *       *   2   *   3       *
    *   3   *   2   *   3   *       *********************
    *************************   
    

提交回复
热议问题