Oracle的行列转换怎么写?
如题。
------解决方案--------------------转接,与此类似
--测试数据
create table t (XH varchar2(10), DDATE date, SXF int);
insert into t
select 1,sysdate,10 from dual union all
select 1,sysdate+1,14 from dual union all
select 1,sysdate+2,23 from dual union all
select 2,sysdate,21 from dual union all
select 2,sysdate+1,24 from dual union all
select 3,sysdate,13 from dual union all
select 3,sysdate+1,22 from dual;
--
create or replace package sp_test
is
type ResultData is ref cursor;
procedure getRstData( rst out ResultData);
end sp_test;
/
create or replace package body sp_test
is
procedure getRstData( rst out ResultData)
is
begin
declare
cursor cur is select distinct (DDATE) from t;
tmp_ddate date;
str varchar2(4000);
begin
str:='select xh';
open cur;
loop
fetch cur into tmp_ddate;
exit when cur%notfound;
str:=str||',sum(decode(to_char(ddate,''yyyymmdd''),'||chr(39)||to_char(tmp_ddate,'yyyymmdd')||chr(39)||',sxf,0)) "'||to_char(tmp_ddate,'yyyymmdd')||'"';
end loop;
str:=str||' from t group by xh';
-- dbms_output.put_line(str);
close cur;
open rst for str;
end;
end;
end sp_test;
/
--输出结果
1 10 14 23
2 21 24 0
3 13 22 0
------解决方案--------------------固定列,就用decode  
非固定列,要用到存储过程或用PL/SQL来做也行
------解决方案--------------------比如说有数据
Name  class score
小明  语文   80
小强  数学   90
小明  英语   89
小强  语文   70
小明  数学   95
小强  英语   85
要求出来
姓名   语文  数学  英语
小明   80    95    89
小强   70    90    85
这时候就以用decode来做
SELECT   NAME 姓名, SUM (DECODE (CLASS, '语文', score, 0)) 语文,
        SUM (DECODE (CLASS, '数学', score, 0)) 数学,
        SUM (DECODE (CLASS, '英语', score, 0)) 英语
   FROM table
GROUP BY NAME
------解决方案--------------------不固定的,参考此贴
http://topic.csdn.net/u/20080416/11/910e40c1-60f1-441f-8b0f-19a969d30f77.html
------解决方案--------------------SQL code
SELECT ID,
        MAX(DECODE(NAME, 'aa', 'aa' )) aa,
        MAX(DECODE(NAME, 'bb', 'bb' )) bb,
        MAX(DECODE(NAME, 'cc', 'cc' )) cc  
  FROM tt GROUP BY ID;