Transpose column to rows

Dave Gray 586 Reputation points
2024-04-05T08:59:01.73+00:00

Hi,

Without using a cursor (if poss) I would like to turn the following data into rows based based upon the integer in column two.

User's image

So I would end up with 5 rows for the first date, 1 for the second etc.

User's image

Can anyone advise on how best to do this pls? Here is the sandbox code ...

DECLARE @Visitors TABLE (TheDate DATE, CountOfVisitors INT);

INSERT @Visitors (TheDate, CountOfVisitors) VALUES(GETDATE()-1, 5 )

INSERT @Visitors (TheDate, CountOfVisitors) VALUES(GETDATE()-2, 1 )

INSERT @Visitors (TheDate, CountOfVisitors) VALUES(GETDATE()-3, 7 );

SELECT * FROM @Visitors;

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,656 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,706 Reputation points
    2024-04-05T20:14:16.1866667+00:00

    it depends on the version of sqlserver you are using. if using sqlserver 2022 you can cross apply to generate_series.

    otherwise you need a series table. you need to know the max visitor count, then insert a row for 1 to max.

    create table Series (number int not null unique)
    declare @max int = 10000;
    declare @i int = 0;
    while (@i < @max) begin
       set @i = @i + 1
       insert Series values(@i)
    end
    

    then just join to your series table:

    select TheDate
    from @Visitors 
    join Series on Series.Number between 1 and CountOfVisitors  
    
    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.