我很难找到如何做到这一点。我一直在寻找好几个小时,但却无法找到可行的解决方案。
我有两张桌子。
TableA - Code, TranDate, Amount
TableB - Code Amount
我希望通过扣除TableA中的金额总和来更新TableB金额(其中a.code = b.code 和a.TranDate> ' A GIVEN DATE'
我必须承认SQL的能力有限。我正在使用SQL Server 2005.
答案 0 :(得分:1)
尝试:
@Date = 'A GIVEN DATE'
UPDATE TableB
SET TableB.Amount = TableB.Amount - (SELECT SUM(TableA.Amount)
FROM TableA as A, TableB
WHERE A.Code = B.Code AND A.TranDate > @Date)
答案 1 :(得分:0)
试试这个:
UPDATE TB
SET
TB.Amount = TB.Amount - TotalDeduction
FROM TableB TB
JOIN (SELECT Code, SUM(Amount) AS TotalDeduction FROM TableA GROUP BY Code) TA ON TA.Code = TB.Code
答案 2 :(得分:0)
declare @date date,
update TableB
set TableB.Amount= TableB.Amount-sum(TableA.Amount) from TableA, TableB
where TableA.code = TableB.code and TableA.TranDate >@date
答案 3 :(得分:0)
使用公用表扩展的简便方法:
with cte as (
select A.Code, sum( A.Amount ) as Amount
from TableA A inner join TableB B on A.Code = B.Code
where A.TranDate > *someDete*
Group by A.Code
)
update B
Set B.amount = CTE.amount
from TableB B inner join CTE on B.Code = CTE.Code
已编辑到期OP评论:
CTE可从sqlserver 2005获得:http://technet.microsoft.com/en-us/library/ms190766(v=sql.90).aspx
在sqlserver 2008上测试查询:http://sqlfiddle.com/#!3/9e424/1/0