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'
           )
        )
2
  • 1
    Should we assume that your desired results are to have 2 and 3 in the val column rather than repeating a val of 1 in 3 different rows? Commented Dec 11, 2012 at 19:11
  • @JustinCave, yes. I will fix that. Commented Dec 11, 2012 at 19:14

1 Answer 1

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 |
Sign up to request clarification or add additional context in comments.

3 Comments

The UNPIVOT requires that all data be of the same type this was my main problem. Thanks.
follow up question what are src and un?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.