您可以使用FOR XML PATH
. 虽然有点难以阅读,但它目前是连接字符串的最简洁的方法。
分解
FOR XML PATH
连接与子选择匹配的所有值
STUFF
删除前导逗号
SQL 语句
SELECT q.CAT
, q.TYPE
, SUBPRODUCT = STUFF((SELECT ', ' + qi.SUBPRODUCT FROM q qi WHERE qi.Cat = q.Cat AND qi.Type = q.Type FOR XML PATH('')), 1, 2, '')
FROM q
GROUP BY
q.CAT
, q.TYPE
测试脚本
;WITH q AS (
SELECT * FROM (VALUES
(1, 1, 1, 'AA')
, (2, 1, 1, 'BB')
, (3, 1, 2, 'CC')
) AS a (ID, CAT, TYPE, SUBPRODUCT)
)
SELECT q.CAT
, q.TYPE
, SUBPRODUCT = STUFF((SELECT ', ' + qi.SUBPRODUCT FROM q qi WHERE qi.Cat = q.Cat AND qi.Type = q.Type FOR XML PATH('')), 1, 2, '')
FROM q
GROUP BY
q.CAT
, q.TYPE