How to concatenate values from previous row to current row in SQL?
SQL interview questions and answers #8
Answer:
DECLARE @t TABLE (
id INT IDENTITY(1,1) PRIMARY key,
drink_name VARCHAR(30)
)
INSERT INTO @t (drink_name)
SELECT * FROM (VALUES ('milk tea'),('lemon tea'),('milk shake')) x(drink_name)
SELECT * FROM @t
SELECT id,
STUFF( (SELECT ', ' + drink_name
FROM @t t2
WHERE t2.id <= t1.id
FOR XML PATH('')),1,2,'') AS drink_name
FROM @t t1
GO