oracle列轉換為行

2021-05-26 15:15:29 字數 1440 閱讀 3914

首先介紹行轉換為列,

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;

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

oracle列轉換為行

首先介紹行轉換為列,oracle行轉換為列是比較常見,網上常見的例子如下 grades表 student subject grade student1 語文 80 student1 數學 70 student1 英語 60 student2 語文 90 student2 數學 80 student2...

Oracle行轉換列SQL語句

select fmonth,sum decode factionid,1,fcount,0 as factionid1,sum decode factionid,2,fcount,0 as factionid2 from select fmonth,factionid,count as fcount...

Oracle中把列值轉換為列名

create table ass acptnum varchar 30 qu name varchar 4000 awname varchar 2000 insert into ass values 15101232097 問題1 答案1 insert into ass values 1510123...