SQL Cursor合并字段

时间:2018-02-01 14:26:16

标签: sql sql-server

以下设置:
https://i.stack.imgur.com/lHM9H.png
(只要您在网站上获得10点声望,您就可以嵌入图片)

我想在第二列中添加所有相同的数字,但我不知道怎么做。输出应如下所示:

+------------+------------+
| 00000030   | 106        |
| 00000001   | 106,107,125|
| 00000002   | 103        |
| 00000002   | 103        |
 and so on ....
+------------+------------+

甚至可以使用简单的SQL,还是必须使用sql游标?

1 个答案:

答案 0 :(得分:0)

当然,有多种方法可以连接它。这是一种方法:

SELECT
    T1.U_BaseCode,
    STUFF((
        SELECT
            ',' + CONVERT(VARCHAR(10), T2.U_FilterCode) AS [text()]
        FROM [TableName] T2
        WHERE T2.U_BaseCode = T1.U_BaseCode
        ORDER BY T2.U_FilterCode
        FOR XML PATH('')
    ), 1, 1, '') AS FilterCodes
FROM [TableName] T1
GROUP BY
    T1.U_BaseCode