SQL query

Hello Experts ,

I have a table test , which has values as like below:

select * from test;

col1 col2 
1	AA
2	BB

Open in new window


Now I want  to get the result as below on SQL Server 2008 version without using pivot:

column_name  data1 data2        
col1 1  2
col2 AA BB

Open in new window

LVL 17
Swadhin Ray Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
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.

Jared_SCommented:
SQL wont support that in any way that is even moderately efficient. Can you process the data outside of SQL?
0
lwadwellCommented:
Agree that it isn't elegant to do this in SQL ... not even sure a PIVOT would work.
This is the SQL I came up with:
;with test as (
select 1 col1, 'AA' col2 union all
select 2 col1, 'BB' col2
)
select column_name, max(data1) data1, max(data2) data2
from (select 'col1' column_name
           , case when rn = 1 then convert(varchar,col1)
             end as data1
           , case when rn = 2 then convert(varchar,col1)
             end as data2
      from (select col1, col2, row_number()over(order by col1) rn from test)v
      union all
      select 'col2' column_name
           , case when rn = 1 then convert(varchar,col2)
             end as data1
           , case when rn = 2 then convert(varchar,col2)
             end as data2
      from (select col1, col2, row_number()over(order by col1) rn from test)v)x
group by column_name

Open in new window

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
Guy Hengel [angelIII / a3]Billing EngineerCommented:
I wonder also about such a requirement, and can confirm that with "sql", you cannot do this.

in ms excel, it would be a "transpose" function ...
0
Swadhin Ray Author Commented:
thanks
0
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
Microsoft SQL Server 2008

From novice to tech pro — start learning today.