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

前端 未结 20 2508
无人及你
无人及你 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:02

    Using Replace Function and FOR JSON PATH

    SELECT T3.DEPT, REPLACE(REPLACE(T3.ENAME,'{"ENAME":"',''),'"}','') AS ENAME_LIST
    FROM (
     SELECT DEPT, (SELECT ENAME AS [ENAME]
            FROM EMPLOYEE T2
            WHERE T2.DEPT=T1.DEPT
            FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) ENAME
        FROM EMPLOYEE T1
        GROUP BY DEPT) T3
    

    For sample data and more ways click here

提交回复
热议问题