oracle列轉換爲行

首先介紹行轉換爲列,

oracle行轉換爲列是比較常見,網上常見的例子如下:

grades表:

student  subject   grade

student1  語文     80

student1  數學     70

student1  英語     60

student2  語文     90

student2  數學     80

student2  英語     10

轉換爲

語文  數學    英語

Student1  80     70      60

Student2  90     80      100

執行語句如下:

Select student,

sum(decode(subject,'語文',grade,null)) "語文",

sum(decode(subject,'數學',grade,null)) "數學",

sum(decode(subject,'英語',grade,null)) "英語"

from grades

group by student order by student;
下面,介紹列轉換爲行的操作:

假設一個表test,記錄如下:

  表頭  id   proc1  proc2   proc3   
  記錄  12   3.4      6.7   12.4   

  想變成如下格式:   
  表頭 id   proc      value   
  記錄  12  proc1       3.4   
  記錄 12   proc2      6.7   
  記錄 12   proc3      12.4  

方法一:採用union all方法(這種方法會隨着字段的增多,變得很長,不推薦)

select id,'proc1',proc1
    from testjac where id=12
    union all
    select id,'proc2',proc2
    from testjac where id=12
    union all
    select id,'proc3',proc3
from testjac where id=12;

方法二:採用decode+系統視圖USER_TAB_COLS(推薦):

select A.id,B.column_name,decode(B.column_name,'PROC1',A.proc1,'PROC2',A.proc2,'PROC3',A.proc3,null) value
from test A,(select column_name from user_tab_cols where column_id>1 and table_name='TEST') B



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章