SELECT customer,
LISTAGG(product, ', ') WITHIN GROUP (ORDER BY order_id) AS products
FROM orders
GROUP BY customer
ORDER BY customer;
-- SQL Server 2017 이상
SELECT customer,
STRING_AGG(product, ', ') WITHIN GROUP (ORDER BY order_id) AS products
FROM orders
GROUP BY customer
ORDER BY customer;
-- SQL Server 2016 이하
SELECT o.customer,
STUFF((
SELECT ', ' + i.product
FROM orders i
WHERE i.customer = o.customer
ORDER BY i.order_id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS products
FROM orders o
GROUP BY o.customer
ORDER BY o.customer;
SELECT customer,
STRING_AGG(product, ', ' ORDER BY order_id) AS products
FROM orders
GROUP BY customer
ORDER BY customer;
LISTAGG 결과는 VARCHAR2 최대 길이(보통 4,000바이트)를 넘으면 오류가 나요. 12.2부터 ON OVERFLOW TRUNCATE를 붙이면 잘라서 보여줘요. 중복 제거는 19c부터 LISTAGG(DISTINCT …)로 돼요.
STRING_AGG는 2017부터 쓸 수 있어요. 그 전 버전은 FOR XML PATH로 이어 붙이고 STUFF로 맨 앞 구분자를 지워요.
정렬은 괄호 안에 ORDER BY로 적어요. 중복 제거는 STRING_AGG(DISTINCT product, ', ')로 해요.