SQL- to append accumlate text from previous row to next row within Table

nononame2021 256 Reputation points
2022-03-31T14:45:28.957+00:00

1 table with drink table

drink table with following drink (3 row in drink table)

mike tea
lemon tea
mike shake


how to prepare a SQL to list out as below:

mike tea
mike tea, lemon tea
mike tea, lemon tea, mike shake

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,682 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,625 questions
{count} votes

9 answers

Sort by: Most helpful
  1. nononame2021 256 Reputation points
    2022-03-31T15:59:22.553+00:00

    anyone know?

    simple example is table contain:

    1
    2
    3

    how to list out the result as below: (how to write a SQL to do that )

    1
    1,2
    1,2,3

    0 comments No comments

  2. Naomi Nosonovsky 7,856 Reputation points
    2022-03-31T16:12:51.03+00:00

    Try:

    INSERT INTO @t (val)
    SELECT * FROM (VALUES
        (NULL -- val - int
        ), (1), (2), (3)) x(val)
    
    SELECT * FROM @t    
    
    SELECT id, val, (SELECT STRING_AGG(val, ', ') WITHIN GROUP (ORDER BY id ) AS val2 FROM @t t2 WHERE t2.id <= t1.id) 
    FROM @t t1
    

  3. nononame2021 256 Reputation points
    2022-03-31T16:38:10.157+00:00

    anyone help?


  4. Naomi Nosonovsky 7,856 Reputation points
    2022-03-31T17:02:25.383+00:00

    Try:

    DECLARE @t TABLE (id INT IDENTITY(1,1) PRIMARY key, val VARCHAR(30))
    
    INSERT INTO @t (val)
    SELECT * FROM (VALUES
        (NULL -- val - int
        ), ('mike tea'), ('lemon tea'), ('miki shake')) x(val)
    
    SELECT * FROM @t    
    
    SELECT id, val, STUFF( (SELECT ', ' + val  FROM @t t2 WHERE t2.id <= t1.id FOR XML PATH('')),1,2,'') AS val2 
    FROM @t t1
    

  5. nononame2021 256 Reputation points
    2022-03-31T17:29:25.79+00:00

    any other simply way to do that?

    just single select?


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.