表A
ITEM BASE_WT BASE_AMT
AAA 50 500
BBB 100 6000
表B
ITEM OUTDAY WT AMT
AAA 20140105 10 100
BBB 20140106 10 600
AAA 20140107 10 100
表A结果
AAA 30 300
BBB 90 5400
MSSQL QUERY
UPDATE A SET
BASE_WT = BASE_WT - X.WT
BASE_AMT = BASE_AMT - X.AMT
FROM A,
(
SELECT ITEM , SUM(B.WT) WT, SUM(B.AMT) AMT
FROM B
WHERE OUTDAY BETWEEN '20140105' AND '20140107'
GROUP BY ITEM
) X
WHERE A.ITEM = X.ITEM
答案 0 :(得分:0)
试试这个:
UPDATE A
SET (BASE_WT, BASE_AMT)
= (SELECT A.BASE_WT - SUM(B.WT), A.BASE_AMT - SUM(B.AMT)
FROM B
WHERE B.OUTDAY BETWEEN '20140105' AND '20140107'
AND B.ITEM = A.ITEM)
WHERE A.ITEM IN (SELECT ITEM FROM B WHERE OUTDAY BETWEEN '20140105' AND '20140107');
外部WHERE条件避免重置(为NULL)A中在子查询中没有相应ITEM的记录。
答案 1 :(得分:0)
update a
set (base_wt, base_amt) = (
select
a.base_wt - x.wt,
a.base_amt - x.amt
from (
select
b.item,
sum(b.wt ) wt,
sum(b.amt) amt
from
b
where
outday between date '2014-01-05' and date '2014-01-07'
group by
item
) x
where
x.item = a.item
)