動態行轉列 oracle環境

2021-06-18 15:42:50 字數 2287 閱讀 9928

參考原文:

練習示例:

select s.stuid,

max(case s.subjectid when 101 then s.score else 0 end) as "語文",

max(case s.subjectid when 102 then s.score else 0 end) as "數學",

max(case s.subjectid when 103 then s.score else 0 end) as "英語"

from ct_test_row2cell s

group by stuid;

***************===原資料 ct_test_row2cell表

1 1 10 101 90.000

2 2 12 101 91.000

3 3 10 102 88.000

4 4 11 102 87.000

5 5 12 103 78.000

6 6 11 103 80.000

7 7 10 103 79.000

8 8 12 102 87.000

9 9 11 101 79.000

***************==統計結果

stuid 語文 數學  英語

1 11    79    87    80

2 10    90    88    79

3 12    91    87    78

*****==

補充:上面寫的case when 是靜態寫法,應用於科目型別已經明確且不需要修改(或修改可能性很小,因為修改的話要修改這個sql的case when),

以下是動態sql

-- 方法一 ----

create or replace package pkg_test1 as

type testresultcur is ref cursor;

end  pkg_test1;

create or replace procedure ct_test_proce_1(rst out pkg_test1.testresultcur ) is

v_subjectid number;

v_sql varchar2(4000);

begin

v_sql := 'select stuid,';

for c in (select distinct subjectid,t.subjname from ct_test_row2cell t order by subjectid)

loop

v_sql:=v_sql||'max(case subjectid when '||c.subjectid||' then score else 0 end) '||c.subjname||',';

end loop;

v_sql:=substr(v_sql,1,length(v_sql)-1);

v_sql:=v_sql||' from ct_test_row2cell group by stuid ';

--dbms_output.put_line(v_sql);

open rst for v_sql;

end;

---方法二---

create or replace procedure ct_test_proce_2 (sqlres out varchar2) is

v_subjcount number(10);

v_sql varchar2(4000);

begin

select count( distinct subjname) into v_subjcount from ct_test_row2cell;

v_sql:='select stuid,';

for i in 1..v_subjcount loop

v_sql:=v_sql||'max(decode(rk,'||i||',rpad(t.subjname || '':'' || t.score,14, '' ''),null)) || ';

end loop;

v_sql:=substr(v_sql,1,length(v_sql)-4);

v_sql:=v_sql||' 科目成績

from

(select t.*, row_number() over(partition by t.stuid order by t.subjname) rk

from ct_test_row2cell t)t

group by t.stuid';

sqlres:=v_sql;

end;

Oracle實現動態行轉列

oracle中要實現行轉列的方式有很多種,比如case when else end wm concat 函式,lag over lead over 函式等,以及11g版本後的pivot函式都可實現。可根據具體的需求選取不同的方式。前兩天恰好一朋友問起如何將如下表1動態轉成表2的形式。表1 表2,ch...

動態行轉列

因狗血的報表展現需求 需要根據每天的新增使用者數量 選取前5個渠道.然後把該渠道當月每一天的新增使用者資料繪製在圖表上 x軸是 日期 y軸是新增使用者數量 畫5條線.這5條線是動態的,每天不同的線條.資料經過後台統計後形成表 statedate,channle id,channle name,new...

動態行轉列

drop table test create table test name varchar 12 scores int insert into test select 周杰倫 230 union select 周星馳 100 union select 成龍 150 union select 李連杰...