• I used a table variable for the tally table in Eric Muller's code. It seemed simpler than creating a permanent table of numbers. I added the following at the top of your query. Otherwise I thought the query was very useful. Much easier than writing all that myself.

    declare @Numbers as Table (N int)

    declare @i int

    SET @i = 1

    while @i <= 32

    Begin

    insert into @Numbers

    select @i

    set @i=@i+1

    END