1

I have a table that looks like this

col1 | col2
-----------
  1  |  a
  2  |  b
  3  |  c

and I want to run a query that makes it look like this

val | colname
-------------
  1 | col1
  2 | col1
  3 | col1
  a | col2
  b | col2
  c | col2

I've read about unpivot and I've figured out how to get the column names. Here's the query I am currently working with.

SELECT 
     * 
FROM 
    myTable 
UNPIVOT (
            val 
        FOR 
            column_name 
        IN (
               SELECT 
                   column_name 
               FROM 
                   USER_TAB_COLUMNS 
               WHERE 
                   table_name = 'myTable'
           )
        )
Community
  • 1
  • 1
John
  • 13,197
  • 7
  • 51
  • 101

1 Answers1

2

Unless I am missing something, why can't you use this. The UNPIVOT requires that all data be of the same type, so you mush cast data as needed:

select value, colName
from
(
  select to_char(col1) col1,
    col2
  from yourtable
) 
unpivot
(
  value
  for colName in (col1, col2)
) 
order by value

See SQL Fiddle with Demo

Result:

| VALUE | COLNAME |
-------------------
|     1 |    COL1 |
|     2 |    COL1 |
|     3 |    COL1 |
|     a |    COL2 |
|     b |    COL2 |
|     c |    COL2 |
Taryn
  • 242,637
  • 56
  • 362
  • 405
  • `The UNPIVOT requires that all data be of the same type` this was my main problem. Thanks. – John Dec 11 '12 at 19:22
  • follow up question what are `src` and `un`? – John Dec 11 '12 at 19:31
  • @johnthexiii they are aliases for the stuff inside the parentheses. They are not needed for Oracle. I am used to SQL Server syntax where it is required. I undated my solution. – Taryn Dec 11 '12 at 19:33