SQL Select to split a 3 column table into 6 columns


I have a 3 column table ordered alphabetically by name.


I need to select all rows in groups of 48, with the first 48 into the first 3 columns, the second 48 into the second 3 columns, the next 48 into the first 3 columns, next into the second 3 columns, and so on until all 16,000 rows are split into two columns alphabetically in groups of 48.


LVL 6
RustyZ32Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

EvilPostItCommented:
Here is an example...

create table #t1 (col1 varchar(10),col2 varchar(10))

insert into #t1 values ('a','a')
--do a load of inserts as an example with different data.

select * from
(select *,ROW_NUMBER() OVER (ORDER BY COL1) AS ROWNUM FROM #t1)a
left outer join (select *,ROW_NUMBER() OVER (ORDER BY COL1) AS ROWNUM FROM #t1)b on a.ROWNUM=b.ROWNUM-3
where (a.ROWNUM-1)/3%2=0

Open in new window

0
SharathData EngineerCommented:
I didn't understand. Can you provide some sample data with expected result?
0
LowfatspreadCommented:
;with cte as (select x.*
                    ,row_number() over (order by name asc) as rn
                from yourtable as x)
,cte1 as (select x.col1,x.col2,x.col3
                ,y.col1 as col4,y.col2 as col5,y.col3 as col6
                ,x.rn
           from cte as x
          left outer join cte as y
             on x.rn=y.rn-48
          where (x.rn / 48) % 2 = 0)
select col1,col2,col3,col4,col5,col6
 from cte1
 order by rn
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.