views:

409

answers:

3

I have a query that always returns one row, with many columns. I would like to turn this into 2 columns and many rows.

Original results:

Col1, Col2, Col3, Col4
----------------------
val1, val2, val3, val4

What I want:

ColName, Value
--------------
Col1,    val1
Col2,    val2
Col3,    val3
Col4,    val4

Is this possible?

EDIT (clarification)

I'm looking for an automatic way of doing this. IE something I can pass results from any query that only returns 1 line.

+3  A: 

sure. Do

select 'Col1' ColName, Col1 Value from srctable union all
select 'Col2', Col2 from srctable union all
select 'Col3', Col3 from srctable union all
select 'Col4', Col4 from srctable
marc
Hmm. That would do the trick. I'm kinda hoping there is an automatic way of doing it, though...
David Oneill
+1  A: 

Are you using Oracle 11g? Did you try pivot and unpivot?

More info here.

Pop
I do have unpivot. This still doesn't do exactly what I want, but I'll split that off into a second question.
David Oneill
Note for posterity: this only works if all your columns are the same return type. You can get around this by casting them all via to_char()
David Oneill
A: 

I'm guessing you don't have the Oracle version with build in Pivot table support. Unfortunately it's never very clean code, as you have to build up each row.

See this older post for an example

transpose-select-results-with-oracle

Wiretap