ORacel行列转换问题

qzb0818 2008-04-22 11:01:42
如何实现如下SQL语句:

先有一Oracle表:

产品 区域 销售额

A 北京 300

B 上海 400

B 广州 350

C 广州 500
...

现要生成以下查询报表,请问如何用SQL语句实现?


产品 北京 上海 广州 ...

A 300 0 0

B 0 400 350

C 0 0 500
...全文
159 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
knowledge_Is_Life 2008-05-01
  • 打赏
  • 举报
回复
不知,帮顶
hebo2005 2008-04-22
  • 打赏
  • 举报
回复
搜索 行列转换
搜索 潇洒老乌龟
HelloWorld_001 2008-04-22
  • 打赏
  • 举报
回复
--测试数据
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
qzb0818 2008-04-22
  • 打赏
  • 举报
回复
非固定列,谁能给个完整的代码?
fxianxian 2008-04-22
  • 打赏
  • 举报
回复
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
hebo2005 2008-04-22
  • 打赏
  • 举报
回复
固定列

select pro 产品,
sum(decdoe(area,'北京',amt,0)) 北京 ,
sum(decdoe(area,'上海',amt,0)) 上海 ,
sum(decdoe(area,'广州',amt,0)) 广州
from table a
group by pro
hebo2005 2008-04-22
  • 打赏
  • 举报
回复
又是行列转换啊
现在变成一天几次了
如果是固定列就用decdoe

sum(decdoe(区域,'北京',销售额,0)) 北京

如果不是固定列就用存储过程去做
kanxue660 2008-04-22
  • 打赏
  • 举报
回复
提问前先搜索下!
mldshlizhi 2008-04-22
  • 打赏
  • 举报
回复
有点难实现,关注中。。。。。。。。。。。
flycbx 2008-04-22
  • 打赏
  • 举报
回复
学习中
xiangs 2008-04-22
  • 打赏
  • 举报
回复
如果是固定行数转换的话,用下面这个比较简单:
select 产品,
sum(decode(区域,'广州',销售额,0)) 广州,
sum(decode(区域,'北京',销售额,0)) 北京,
sum(decode(区域,'上海',销售额,0)) 上海
from test_table
group by 产品


hebo2005 2008-04-22
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 qzb0818 的回复:]
没有人解决这个实际问题?
[/Quote]
上面这么多人告诉你方法,居然说没有人解决这个问题
另外要善于搜索啊
这个问题已经向日经问题演变了,天天有人问,难道就不会自己搜索下嘛
qzb0818 2008-04-22
  • 打赏
  • 举报
回复
没有人解决这个实际问题?

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧