我有两个表:CustomerOrder和OrderItem。
CustomerOrder
具有以下列:ID, CustomerId, DateOrdered, IsCreditCardPayment
。
OrderItem
具有以下列:OrderId(FK from CustomerOrder), ProductId, Quantity, Price
。
我需要做的是计算当客户使用信用卡付款时银行从我的业务中提取的准备金金额。拨款是2%。
我的问题是如何将ID保存在用信用卡支付的订单的数组中,然后告诉SQL Server仅乘以数组中具有相同ID的订单项的数量和价格?
到目前为止,我有这个问题:
SELECT ID FROM CustomerOrder
WHERE DateOrdered BETWEEN '2000-01-01' AND '2000-02-01'
IF( ? )
BEGIN
SELECT ID FROM CustomerOrder
WHERE IsCreditCardPayment = 1
END
FROM CustomerOrder
我正在使用:
Sql Server 14.0.17230.0
答案 0 :(得分:2)
您不需要保存这些ID。只需直接更新它们即可:
UPDATE CustomerOrder SET
ProvisionAmount = 0.02 * OrderAmount
WHERE DateOrdered BETWEEN '2000-01-01' AND '2000-02-01' and IsCreditCardPayment = 1
您可能还想处理已更新的订单,例如通过添加ProvosionAmount is null
或添加一些标志。
如果您确实需要“保存”这些ID,则可以使用子查询:
UPDATE AnotherTable SET SomeField = ... where OrderId in (SELECT ID FROM
CustomerOrder
WHERE DateOrdered BETWEEN '2000-01-01' AND '2000-02-01' )
或将它们保存到临时表或表变量中:
-- Use table variable
DECLARE @OrderIDs table(OrderId int)
insert into @OrderIDs
SELECT ID FROM
CustomerOrder
WHERE DateOrdered BETWEEN '2000-01-01' AND '2000-02-01'
-- Create a new temp table
SELECT ID FROM
insert into #OrderIDs
CustomerOrder
WHERE DateOrdered BETWEEN '2000-01-01' AND '2000-02-01'
-- Insert into pre-created table
CREATE TABLE #OrderIDs(OrderId int)
insert into #OrderIDs
SELECT ID FROM
CustomerOrder
WHERE DateOrdered BETWEEN '2000-01-01' AND '2000-02-01'
,然后使用上述方法之一来更新数据。