我有2张桌子。
股票:
ID Name Quantity
1 Table 100
2 Desk 200
和第二个表转移:
ID Name AddDate AddQT RemoveDate RemoveQT Agent
1 Table 6/19/2015 10:03:06 AM 10 alex mortage
2 Table 6/19/2015 10:03:06 AM 15 linda raven
如何根据转移表格列Quantity
或AddQT
更新广告资源表中的列RemoveQT
?
转移表通过用户输入(数量值)更新,1条记录可能有一个添加日期,因此它是一个"添加数量"操作。可以在SQL中注册另一条记录,以便通过用户输入删除数量。
答案 0 :(得分:0)
UPDATE语句可以这样做:
UPDATE Stock SET Quantity = sum(isnull(AddQt, 0) - isnull(RemoveQt, 0))
FROM Stock
LEFT JOIN Transfers on Transfers.Name = Stock.Name
GROUP BY Stock.Name, Transfers.Name
如果您需要它是自动的,您只需在Transfers:
的触发器中执行此语句CREATE TRIGGER [Transfers_UpdateStock] ON [Transfers] AFTER INSERT,DELETE,UPDATE
AS
BEGIN
UPDATE Stock SET Quantity = sum(isnull(AddQt, 0) - isnull(RemoveQt, 0))
FROM Stock
LEFT JOIN Transfers on Transfers.Name = Stock.Name
WHERE Stock.Name in inserted.Name or Stock.Name in deleted.Name
GROUP BY Stock.Name, Transfers.Name
END
GO
答案 1 :(得分:0)
Update stock
set quantity = quantity +
(Select sum(coalesce(addqt,0))-(sum(coalesce(removeqt,0))*-1)
From transfers t
Where t.id = stock.id)
Where Id in (select id from transfers)
/ *在公共交通工具上做到了这一点,所以无法验证,但我不知道* /
/ *和谐相加是多余的* /