How to write sql query to get the outout?

Ramana Kopparapu 306 Reputation points
2023-06-14T10:32:02.9433333+00:00

My output should be in this way:

1

1 2

1 2 3

1 2 3 4

Thanks in Advance.

Could anyone please look into this and do needful?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,492 questions
{count} votes

Accepted answer
  1. Yitzhak Khabinsky 26,576 Reputation points
    2023-06-14T18:25:19.5533333+00:00

    Hi @Ramana Kopparapu,

    Please try the following solution. It is using T-SQL and its XQuery.

    -- DDL and sample data population, start
    DECLARE @tbl TABLE (ID INT PRIMARY KEY);
    INSERT @tbl (ID) VALUES
    (1), (2), (3), (4), (5);
    -- DDL and sample data population, end
    
    SELECT * 
    	, CAST(N'' AS XML).query('
    		for $i in (1, 2, 3, 4, 5) 
    		return if ($i le sql:column("ID")) then $i else ()
    	').value('.', 'VARCHAR(100)') AS result
    FROM @tbl;
    
    
    

    Output

    ID result
    1 1
    2 1 2
    3 1 2 3
    4 1 2 3 4
    5 1 2 3 4 5
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-06-14T21:44:29.7033333+00:00

    Here is a query without XML, but which requires SQL 2022:

    
    SELECT value, 
           (SELECT string_agg(convert(varchar, b.value), ' ') WITHIN GROUP (ORDER BY b.value)
            FROM   generate_series(1, a.value) b)
    FROM   generate_series(1, 5) a
    
    
    0 comments No comments

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.