views:

25

answers:

1

I have a table with this structure:

date  colname   value
----------------------------
date  col1name  col1's value  
date  col2name  col2's value  
date  col3name  col3's value  

Now I need to convert it into this structure:

date col1name       col2name      col3name  
-----------------------------------------------
date col1's value   col2's value  col3's value  

Is it possible?

+2  A: 

You want a pivot table:

  SELECT t.date,
         MAX(CASE WHEN t.colname = 'col1name' THEN t.value END) AS col1name,
         MAX(CASE WHEN t.colname = 'col2name' THEN t.value END) AS col2name,
         MAX(CASE WHEN t.colname = 'col3name' THEN t.value END) AS col3name
    FROM TABLE t
GROUP BY t.date

If you want to make it dynamic based on the colname value, you'll need to use dynamic SQL because you need to get the list of colname values first before constructing the actual query.

Oracle didn't add PIVOT/UNPIVOT support until 11g. The CASE expression is supported 9i+; prior to 9i you'd have to use DECODE...

OMG Ponies
Hi Ponies. Thanks for your reply. But it is not about order, it is about flatten the previous table. i.e. 'importing the data' in your answer, I am not sure how to do that.
sarahTheButterFly
@sarahTheButterFly: Updated when I saw you change the formatting.
OMG Ponies
Yeah, it works! Thankyou!
sarahTheButterFly