Q
Problem solve Get help with specific problems with your technologies, process and projects.

Select columns as rows

I have a table with four fixed columns, which have to be converted as rows in the SQL output.

I have a table like this:

COLA COLB COLC COLD
 1    2    3    4
 5    6    7    8

And I need SQL output like the following:

COLX COLY
 A    1
 A    5
 B    2
 B    6
 C    3
 C    7
 D    4
 D    8

So I have four fixed columns, which have to be converted as rows.

This can be done with a UNION, with one SELECT per column:

select 'A'  as COLX 
     , COLA as COLY
  from yourtable 
union all 
select 'B'
     , COLB 
  from yourtable 
union all 
select 'C'
     , COLC 
  from yourtable 
union all 
select 'D'
     , COLD 
  from yourtable
order 
    by COLX, COLY
This was last published in January 2006

Dig Deeper on Oracle and SQL

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide.com

SearchDataCenter

SearchContentManagement

SearchHRSoftware

Close