读书人

高分求SQL高手快来解决方案

发布时间: 2012-01-13 22:43:29 作者: rapoo

高分求SQL,高手快来
假设有一下3张表:
学生表
============================
学生编号|姓名
1|张三
2|李四
3|王五


课程表
============================
课程编号|名称
1|语文
2|数学
3|历史
4|物理

成绩表
============================
学生编号|课程编号|分数
1|1|80
1|2|81
1|3|82
1|4|83
2|1|70
2|2|71
2|3|72
1|4|73
3|1|90
3|2|91
3|3|92
3|4|93


问题:如何得到一下报表数据?(1)能否用一个SQL语句实现?(2)如果不能,应该怎么办
报表
============================
|语文|数学|历史|物理
张三|80|81|82|84
李四|70|71|72|74
王五|90|91|92|94



[解决办法]
--如:
Select a.姓名,
sum(decode(b.名称,'语文',c.分数,0)) as 语文,
sum(decode(b.名称,'数学',c.分数,0)) as 数学,
sum(decode(b.名称,'物理',c.分数,0)) as 物理,
sum(decode(b.名称,'历史',c.分数,0)) as 历史
from 学生表 a ,课程表 b ,成绩表 c
Where a.学生编号=c.学生编号 and b.课程编号=c.课程编号
group by a.姓名
[解决办法]
你的要求类似下面这个,需要写个存储过程


--测试数据
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
[解决办法]
楼主看下我的blog:纵向记录横向显示的问题:http://blog.csdn.net/kinglht
[解决办法]
我觉得,最好的办法是查出每个学生每门课的成绩,然后在程序里将他们组合成你想要的格式。只要达到了要求就好,没必要非得在sql语句中查成你想要的形式。常规方法查出来了,在程序里进行组合就没什么难度了。

读书人网 >oracle

热点推荐