日期:2014-05-17  浏览次数:20702 次

(100)求助一条SQL语句或解决办法,难度★★★★★,高手快来救命.
现有问题如下:

有表A如下:
ID     Name       YD       JE
1       张三       1         12
2       李四       1         33
3    王五       1         24
4       张三       2         5
5       张三       3         58
6       张三       7         85
7       张三       8         45
8       张三       12       52
9       李四       3         25
10     李四       4         14
11     李四       6         25
12     王五       11       25

现求一条SQL语句,或者别的办法,要求实现查询出的结果如下:
Name   1月   2月   3月 4月 5月 6月 7月 8月 9月 10月     11月 12月
张三   12       5         58                                             85         45                                             52
李四   33                 25         14                     25
王五   24                                                                                                                 25

请高手帮忙,谢谢!


------解决方案--------------------
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 (YD) from A order by yd;
tmp_yd number;
str varchar2(4000);
begin
str:= 'select Name ';
open cur;
loop
fetch cur into tmp_yd;
exit when cur%notfound;
str:=str|| ',sum(decode(to_char(yd), '||chr(39)||to_char(tmp_yd)||chr(39)|| ',je,0)) "to_char(yd)|| '月 ' " ';
end loop;
str:=str|| ' from a group by name ';
close cur;
open rst for str;
end;
end;
end sp_test;

------解决方案--------------------
select
max(decode(t.yd,1,je,null)),
max(decode(t.yd,2,je,null)),
...
max(decode(t.yd,12,je,null))
from table t
group by t.Name