例如
变成这样的效果
WITH CTE_TableName AS (
SELECT spdm, djbh
FROM SPJHDMX)
SELECT t0.spdm
, STUFF((
SELECT ',' + t1.djbh
FROM CTE_TableName t1
WHERE t1.spdm = t0.spdm
ORDER BY t1.djbh
FOR XML PATH('')), 1, LEN(','), '') AS djbhs
FROM CTE_TableName t0
GROUP BY t0.spdm
ORDER BY spdm;
这个sqlServer 版本<=2016这样写
SELECT spdm, STRING_AGG(djbh, ',') WITHIN GROUP (ORDER BY djbh) AS djbhs
FROM SPJHDMX
GROUP BY spdm
ORDER BY spdm;
SQL Server ≥ 2017 或者 Azure SQL 这样写