Rajanand Ilangovan
Rajanand Ilangovan

Rajanand Ilangovan

How to concatenate values from previous row to current row in SQL?

How to concatenate values from previous row to current row in SQL?

SQL interview questions and answers #8

Rajanand Ilangovan's photo
Rajanand Ilangovan
·Apr 9, 2022·

1 min read

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

image.png

Source

Impressum