動態行轉列 oracle環境

參考原文:http://idata.blog.51cto.com/4581576/1071030

http://www.cnblogs.com/kerrycode/archive/2010/07/28/1786547.html

練習示例:
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;

 

發佈了13 篇原創文章 · 獲贊 3 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章