Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

sql - ORACLE unpivot columns to rows

ORACLE 10 Hi, I was reading several posts here and i did not come up to a simple solution

I have this data:

Transacion_ID  GROSS_AMOUNT  DISCOUNT_AMOUNT 
1,             10 ,          -1 
2,             1002 ,        -14 
3,             36 ,          -5 

And I need to unpivot to get

Transacion_ID  TYPE     AMOUNT 
1,             GROSS ,  10 
1,             DISC  ,  -1 
2,             GROSS ,  1002 
2,             DISC  ,  -14 
3,             GROSS ,  36 
3,             DISC  ,  -5 

My first approach was to split this in two queries and then just UNION ALL boths results, but this run every 5 hours and has several joins, so spliting means nearly duplicate exec time. I was looking for something like pivot/unpivot in oracle 10.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

Select * From (
Select 
Transacion_ID,
Case When C.lvl = 1 Then 'GROSS'
     When C.lvl = 2 Then 'DISC'
End TYPE,
Case When C.lvl = 1 Then GROSS_AMOUNT
     When C.lvl = 2 Then DISCOUNT_AMOUNT
End AMOUNT
From T
cross join (select level lvl from dual connect by level<=2) c     
) where amount is not null
order by 1

SQL DEMO

This query is based on method mentioned here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...