根据前一行值连接字符串

Concatenating strings based on previous row values

考虑以下输入:

ID
--------
33
272
317
318

我需要以某种方式获得以下结果:

Result
--------
/33
/33/272
/33/272/317
/33/272/317/318

如何使用单个 SELECT 语句实现此目的?

使用 CROSS APPLYFOR XML PATH():

;WITH Cte AS(
    SELECT *,
        RN = ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
    FROM tbl
)
SELECT *
FROM Cte c
CROSS APPLY(
    SELECT '/' + CONVERT(VARCHAR(10), ID)
    FROM Cte
    WHERE rn <= c.rn
    FOR XML PATH('')
)x(s)