为COMMA分隔符创建多行

时间:2017-09-28 04:56:58

标签: sql-server

示例数据:

表A

  BillID    ID_B
  --------------
  122        1
  122        2

表B

  ID_B     Name         
  ------------------
    1      Jakarta              
    2      Malang
    3      Wonosobo

预期结果:

 BillID     Name
 ------           -----------------
  122         Jakarta, Malang

TableA.ID_B = TableB.ID_B

2 个答案:

答案 0 :(得分:1)

SELECT STUFF((
    SELECT
        ',' + [Name]
    FROM
        B AS B
    WHERE
        B.ID_B IN (SELECT ID_B FROM A)
    FOR XML PATH('')), 1, 1, '') AS [Name]

答案 1 :(得分:1)

SELECT BillID,STUFF((SELECT ',' + Name
FROM TABLEB AS T2
WHERE T2.ID_B = T1.ID_B
FOR XML PATH('')),1,1) AS Name FROM TABLEA AS T1

希望这有帮助!