请教SQL语句
两个表:
表1 表2
序号(PK) 总数 余数 序号(FK) 减数
1 100 0 1 10
2 99 0 1 20
3 56 0 1 30
2 40
2 50
两表以序号字段一对多关联。
要求:
表1的余数列=表1的总数列-表2相应序号的减数列之和
即表1结果:
序号(PK) 总数 余数
1 100 40
2 99 9
3 56 0
语句该怎么写?能用一句语句实现吗?
(UPDATE 表1 SET 表1.余数=表1.总数-SUM(表2.减数)
WHERE 表1.序号=表2.序号????)
问题点数:100、回复次数:5Top
1 楼progress99(如履薄冰)回复于 2004-04-02 13:59:30 得分 0
update A
set A.余数=A.总数-B.减数
from 表1 A
left join
(select 序号,sum(减数) as 减数
from 表2
group by 序号
) as
B on B.序号=A.序号Top
2 楼klan(因帅被判7年)回复于 2004-04-02 14:01:48 得分 5
update A
set A.余数=A.总数-B.减数
from 表1 A
left join
(select 序号,sum(减数) as 减数
from 表2
group by 序号
) as
B on B.序号=A.序号
Top
3 楼progress99(如履薄冰)回复于 2004-04-02 14:05:01 得分 90
create table 表1(序号 int, 总数 int, 余数 int )
insert into 表1
select 1 , 100 , 0
union
select 2 , 99 , 0
union
select 3 , 56 , 0
create table 表2(序号 int, 减数 int )
insert into 表2
select 1 , 10
union
select 1 , 20
union
select 1 , 30
union
select 2 , 40
union
select 2 , 50
update A
set A.余数=A.总数-isnull(B.减数,0)
from 表1 A
left join
(select 序号,isnull(sum(减数),0) as 减数
from 表2
group by 序号
) as
B on B.序号=A.序号
select * from 表1
測試結果
1 100 40
2 99 9
3 56 56
Top
4 楼myflok(老虎爱吃肉)回复于 2004-04-02 14:16:45 得分 5
update A
set A.余数=A.总数-B.减数
from 表1 A
,(select 序号,sum(减数) as 减数
from 表2
group by 序号
) as
B where B.序号=A.序号Top
5 楼wyb0026(小小)回复于 2004-04-02 14:31:17 得分 0
select a.序号,a. 总数 from ,a.总数-sum(b.减数) 表1 a inner join 表2 b on a.序号= b.序号
group by a.序号,a. 总数Top




