How to “Implode” (de-normalize/concat) multiple columns into a single column?

后端 未结 4 1945
别跟我提以往
别跟我提以往 2021-01-17 23:46

I have a query which outputs something like this:

+-------+----+--------------+
| F_KEY | EV | OTHER_COLUMN |
+-------+----+--------------+
| 100   | 1  | ..         


        
4条回答
  •  不思量自难忘°
    2021-01-18 00:15

    here is the best concatenation method, it will not expand special characters like other XML methods:

    --Concatenation with FOR XML & eliminating control/encoded char expansion "& < >"
    set nocount on;
    declare @YourTable table (RowID int, HeaderValue int, ChildValue varchar(5))
    insert into @YourTable VALUES (1,1,'CCC')
    insert into @YourTable VALUES (2,2,'B<&>B')
    insert into @YourTable VALUES (3,2,'AAA')
    insert into @YourTable VALUES (4,3,'
    ') insert into @YourTable VALUES (5,3,'A & Z') set nocount off SELECT t1.HeaderValue ,STUFF( (SELECT ', ' + t2.ChildValue FROM @YourTable t2 WHERE t1.HeaderValue=t2.HeaderValue ORDER BY t2.ChildValue FOR XML PATH(''), TYPE ).value('.','varchar(max)') ,1,2, '' ) AS ChildValues FROM @YourTable t1 GROUP BY t1.HeaderValue

    OUTPUT:

    HeaderValue ChildValues
    ----------- ---------------
    1           CCC
    2           AAA, B<&>B
    3           
    , A & Z (3 row(s) affected)

提交回复
热议问题