求教:这样的SQL如何写(有关SUM)

beyondflight 2007-07-25 10:32:07
有一张表:INFO

字段1 字段2 字段3
-----------------
A 25
B 10
B 20
C A 10
C 25
B A,C 20

要求对应字段1、字段2,做字段3的合计,实际上就是得到:
A 55 即(25+10+20)
B 50 即(10+20+20)
C 55 即(10+25+20)

如果只是对应字段1,统计字段3的合计,那就简单了:
select 字段1,sum(字段3) from info group by 字段1

但现在要把字段2的信息也考虑进去,这样的SQL如何写?
(字段2要么为空,要么就是字段1与逗号的组合。)
...全文
204 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
dsy0520 2007-07-26
  • 打赏
  • 举报
回复
学习ing
beyondflight 2007-07-26
  • 打赏
  • 举报
回复
我先试一下,先谢谢!!!
hongqi162 2007-07-26
  • 打赏
  • 举报
回复
create or replace package sp_Info
is
type ResultData is ref cursor;
procedure getResultData( rst out ResultData );
end sp_Info;
/
create or replace package body sp_Info
is
procedure getResultData( rst out ResultData )
is
s varchar2(100);
i int;
f int;
cursor cur is select c2,c3 from info where c2 is not null;
begin
Select Count(*) Into i From User_Tables Where Table_Name = upper('TEMPInfo');
If i < 1 Then
execute immediate 'create global temporary table TEMPInfo(c1 varchar2(10),c3 int)On Commit PRESERVE Rows';
end if;
open cur;
loop
fetch cur into s,f;
exit when cur%notfound;
i:=instr(s,',',1);
while i>0
loop
execute immediate 'insert into tempinfo values('''||substr(s,1,i-1)||''','||f||')';
s:=substr(s,i+1,length(s)-i);
i:=instr(s,',',1);
end loop;
execute immediate 'insert into tempinfo values('''||s||''','||f||')';
end loop;
close cur;
execute immediate 'insert into tempInfo select c1,c3 from info where c2 is null';
open rst for 'select c1,sum(c3) from tempInfo group by c1';
end getResultData;
end sp_Info;
beyondflight 2007-07-26
  • 打赏
  • 举报
回复
to icefirelxb(icefire)

数据库力的表已经这样了,不太容易再去改数据表。

承包人 参与人 承包项目日工资
-----------------
A 25
B 10
B 20
C A 10
C 25
B A,C 20

icefirelxb 2007-07-26
  • 打赏
  • 举报
回复
其他应该都好办,奇怪的是,楼主的字段2里,怎么会出现A,C这种数据,那就还可能会有其他乱七八糟的组合了。到底这里是怎么回事呢?
beyondflight 2007-07-26
  • 打赏
  • 举报
回复
to hongqi162(失踪的月亮)

我这里还是想用SQL去写,你那里能否帮一下,我这里也着急,月底了,要出报表啦。


(我已经给帖子加了分)。
hongqi162 2007-07-26
  • 打赏
  • 举报
回复
如果用一条sql语句来实现比较麻烦
hongqi162 2007-07-26
  • 打赏
  • 举报
回复
麻烦的是将A,C进行拆分,
beyondflight 2007-07-26
  • 打赏
  • 举报
回复
完了,报表的其它部分都写完了,就等这最后一锤了,真的没戏了?
DragonBill 2007-07-26
  • 打赏
  • 举报
回复
没法直接用SQL, 要写PL/SQL

17,086

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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