oracle行轉列、列轉行

來源:互聯網
上載者:User

標籤:blog   http   io   ar   strong   art   div   sp   log   

 

一、行轉列

需要將如下格式

轉換為:

 

這就是最常見的行轉列,主要原理是利用decode函數、聚集合函式(sum),結合group by分組實現的

 

[sql] view plaincopy
  1. create table test(  
  2.        id varchar2(255) primary key not null,  
  3.        name varchar2(255),  
  4.        course varchar2(255),  
  5.        score varchar2(255)  
  6. );  
  7. insert into test values(sys_guid(),‘zhangsan‘,‘語文‘,85);  
  8. insert into test values(sys_guid(),‘zhangsan‘,‘數學‘,78);  
  9. insert into test values(sys_guid(),‘zhangsan‘,‘英語‘,90);  
  10. insert into test values(sys_guid(),‘lisi‘,‘語文‘,73);  
  11. insert into test values(sys_guid(),‘lisi‘,‘數學‘,84);  
  12. insert into test values(sys_guid(),‘lisi‘,‘英語‘,92);  

行轉列SQL語句為:

[sql] view plaincopy
  1. select t.name,   
  2.   sum(decode(t.course, ‘語文‘, score,null)) as chinese,   
  3.   sum(decode(t.course, ‘數學‘, score,null)) as math,   
  4.   sum(decode(t.course, ‘英語‘, score,null)) as english   
  5. from test t   
  6. group by t.name   
  7. order by t.name   


二、列轉行

將如下格式

轉換為

 

這就是最常見的列轉行,主要原理是利用SQL裡面的union

 

[sql] view plaincopy
  1. create table test(  
  2.        id varchar2(255) primary key not null,  
  3.        name varchar2(255),  
  4.        ch_score   varchar2(255),  
  5.        math_score varchar2(255),  
  6.        en_score   varchar2(255)  
  7. );  
  8.   
  9. insert into test values(sys_guid(),‘zhangsan‘,88,76,90);  
  10. insert into test values(sys_guid(),‘lisi‘,91,67,82);  

列轉行SQL語句為:

[sql] view plaincopy
    1. select name, ‘語文‘ COURSE , ch_score as SCORE from test    
    2. union select name, ‘數學‘ COURSE, MATH_SCORE as SCORE from test    
    3. union select name, ‘英語‘ COURSE, EN_SCORE as SCORE from test    
    4. order by name,COURSE 

oracle行轉列、列轉行

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.