Oracle列轉換為行

來源:互聯網
上載者:User

首先介紹行轉換為列,

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

執行語句如下:

  1. Select student,  
  2.   
  3. sum(decode(subject,'語文',grade,null)) "語文",  
  4.   
  5. sum(decode(subject,'數學',grade,null)) "數學",  
  6.   
  7. sum(decode(subject,'英語',grade,null)) "英語"  
  8.   
  9. from grades  
  10.   
  11. group by student order by student;  
  1. Select student,sum(decode(subject,'語文',grade,null)) "語文",sum(decode(subject,'數學',grade,null)) "數學",sum(decode(subject,'英語',grade,null)) "英語"from gradesgroup 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方法(這種方法會隨著欄位的增多,變得很長,不推薦)

  1. select id,'proc1',proc1  
  2.     from testjac where id=12  
  3.     union all  
  4.     select id,'proc2',proc2  
  5.     from testjac where id=12  
  6.     union all  
  7.     select id,'proc3',proc3  
  8. from testjac where id=12;  
  1. 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',proc3from testjac where id=12;  

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

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.