关于sql计算次数重复的问题 (50分)

C

cosmile

Unregistered / Unconfirmed
GUEST, unregistred user!
table1中记录为:
code name kind money
01 corp1 01 100
01 corp1 02 150
02 corp2 01 200

table2中记录为
code name kind money
01 corp1 01 150
01 corp1 02 200
01 corp1 03 100
02 corp2 01 300
03 corp3 01 400
目的是统计相同code(name)记录的money总和和增长,放在同一个表里
开始写的代码如下
select table1.Code, table2.Name, sum(table1.money), sum(table2.money), (sum(table1.money)-sum(table2.money))/sum(table2.money)
from table1 join table2 on table1.code=table2.code
group by table1.Code, table1.Name
发现有两个问题
1.重复计算问题:该程序计算code为01的结果是实际的几倍(code2正常),可是,分别计算table1和table2的sum(money)时
结果是正确的,怀疑是 table1.code=table2.code该语句造成的,可不知怎么改
2.对于table2中的新code,我想体现在新表中,有什么方法可以实现

谢谢
 
你这两个表的结构是一样的
你可以把两个表的记录都加到一个表中
然后再计算
 
select a.code,a.name,sum(a.money),sum(b.money),sum(a.money)-sum(b.money) from
(select Code, Name, sum(money) money from table1 group by code, name) a,
(select Code, Name, sum(money) money from table2 group by code, name) b
where a.code=b.code
group by a.code,a.name
 
谢谢两位的回复,思路是一样的吧
svw0506,调试时提示第二个select处有问题,我没有这么用过select命令
不知道怎么改
 
我用oracle是可以的,不知你用的是什么数据库。
这是子查询,你找一下资料,看你那种数据类似的结构怎样写
 
不能用连接表,可以用Union解决

select code,name,sum(money1) ,sum(money2),(sum(money1)-sum(money2))/sum(money2)
from
(
select table1.code,table1.name,table1.money as money1,0 as money2
from table1
union all
select table2.code,table2.name,0 as money1,table2.money as money2
from table2
) as a
group by code,name
 
我是在delphi里用sql
我再去看看
 
我用delph的Tquery控件,
无法实现select的嵌套
select * from
(select ... ) a
...
调试告诉我第二个select出错
这是为什么
请大家帮忙看看
 
大家帮忙啊
 
非常感谢
 
顶部