日期:2014-05-17 浏览次数:21064 次
select pro 产品, sum(decdoe(area,'北京',amt,0)) 北京 , sum(decdoe(area,'上海',amt,0)) 上海 , sum(decdoe(area,'广州',amt,0)) 广州 from table a group by pro
------解决方案--------------------
SQL> SQL> WITH A AS (SELECT 'A' 產品,'北京' 區域,300 銷售額 FROM DUAL 2 UNION 3 SELECT 'B' 產品,'上海' 區域,400 銷售額 FROM DUAL 4 UNION 5 SELECT 'B' 產品,'廣州' 區域,350 銷售額 FROM DUAL 6 UNION 7 SELECT 'C' 產品,'廣州' 區域,500 銷售額 FROM DUAL 8 ) 9 select 產品,NVL(MAX(DECODE(區域,'北京',銷售額)),0) 北京, 10 NVL(MAX(DECODE(區域,'上海',銷售額)),0) 上海, 11 NVL(MAX(DECODE(區域,'廣州',銷售額)),0) 廣州 12 FROM A 13 GROUP BY 產品 SQL> / 產品 北京 上海 廣州 ---- ---------- ---------- ---------- A 300 0 0 B 0 400 350 C 0 0 500
------解决方案--------------------
--测试数据
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
------解决方案--------------------
搜索 行列转换
搜索 潇洒老乌龟
------解决方案--------------------