SQL初学者问题:用表1中的XX列值减去表2中的XX列值

来源:百度知道 编辑:UC知道 时间:2024/06/23 17:52:53
情况是这样: 表1和表2都有 XX列,我现在想批量更新表1中的XX列(肯定要加WHERE语句)让表1符合条件的每条记录XX列值减去表2中对应的记录中的XX列值,请给条示范语句。。。。回答越详细越好,解决问题有追加。。。。谢谢
PS:语句中可能还有其他运算,主要是这条解决不了,- -o,SQL没学多久。
hao le

你说的是XX列 都是什么数据类型?

update 表1 set a.表1xx列=a.表1xx列-b.表2XX列 from 表1 a ,表2 b
where 条件

建议你更新的时候先使用select 语句查询一下。

你可以先把表2按 char 分组呀!

select char ,sum(numeric) as numeric from 表2 group by char
然后在构造个零时表出来
select char ,sum(numeric) as numeric into test from 表2 group by char
使用零时表跟表1连接呀!!

update 表1 set a.num=a.num-b.numeric from 表1 a ,test b
where a.char=b.char

两表必须要有连接列(连接关键字),一般是ID列,如USERID,要根据连接关键字来更新其它列。
设您的表1 (USERID VARCHAR(10),QTY INT)
表2 (USERID VARCHAR(10),QTY INT)
这样更表1的QTY这一列:
UPDATE 表1 set 表1.QTY=表1.QTY-表2.QTY from 表1,表2 where 表1.USERID=表2.userid
========================================================

这样就行了:
UPDATE 表1
set numeric=表1.numeric-isnull((select sum(表2.numeric) from 表2 where 表2.char=表1.char),0)

1、create view 临时视图 as select char char,sum(numeric) numeric from 表2 group by char;
2、update 表1.a set a.num=(a.num-(sele