SQL: 如何用计算更新所有行?
SQL: How to update all rows with a calculation?
我正在尝试根据订单 sub-total
和 tax
添加披萨订单的 total price
。我一直收到一条错误消息,指出子查询使用此命令返回了超过 1 个值:
DECLARE @orderTotal AS INT
SET @orderTotal = (SELECT(SUM((orderSubtotal+tax) * (1 - discountAmount)))
FROM OrderProcessing GROUP BY orderID)
UPDATE OrderProcessing
SET orderTotalAmount = @orderTotal
discountAmount
等于 0.2
之类的小数,表示 20%
折扣。
首先,这是错误的做法,除非您希望所有订单在 orderTotalAmount
列中具有相同的值。
我想您可能正在寻找这样的东西:
UPDATE OrderProcessing
SET orderTotalAmount = (orderSubtotal + tax) * (1 - discountAmount)
其次,我认为您的第一个查询中的括号过多。
您实际上可以使用某些函数将子查询返回的行限制为一行。
MYSQL:
SELECT column_name(s)
FROM table_name
LIMIT number;
甲骨文:
select *
from
( //your query here )
where ROWNUM = 1;
或者:
SELECT column_name(s)
FROM table_name
FETCH FIRST N ROWS;
希望对您有所帮助:)
我认为您不需要分组依据,但它应该类似于
UPDATE OrderProcessing o
SET orderTotalAmount =
(SELECT(SUM((orderSubtotal + tax) * (1 - discountAmount)))
FROM OrderProcessing
WHERE orderID = o.orderId)
否则,如错误所述,子查询 returns 多条记录。
DECLARE @orderTotal INT, @orderID int
SELECT @orderTotal = SUM((orderSubtotal+tax) * (1 - discountAmount))
FROM OrderProcessing
WHERE orderID = @orderID
GROUP BY orderID
UPDATE OrderProcessing
SET orderTotalAmount = @orderTotal
WHERE orderID = @orderID
如果我理解正确,您需要使用唯一值
更新 OrderProcessing table 中的许多行
原始查询 returns 每个 orderID 一行。
之后您想要更新 orderTotalAmount,但您没有指定哪个 orderID。
显然,您希望以相同的方式更新所有订单。
为此,您需要 sfrutig 方法。
您需要在查询中指定您正在处理的 orderID,返回一行。
并循环使用它来更新所有订单。
由于我没有足够的积分,我无法将此评论放在 sfrutig 的解决方案旁边。
我正在尝试根据订单 sub-total
和 tax
添加披萨订单的 total price
。我一直收到一条错误消息,指出子查询使用此命令返回了超过 1 个值:
DECLARE @orderTotal AS INT
SET @orderTotal = (SELECT(SUM((orderSubtotal+tax) * (1 - discountAmount)))
FROM OrderProcessing GROUP BY orderID)
UPDATE OrderProcessing
SET orderTotalAmount = @orderTotal
discountAmount
等于 0.2
之类的小数,表示 20%
折扣。
首先,这是错误的做法,除非您希望所有订单在 orderTotalAmount
列中具有相同的值。
我想您可能正在寻找这样的东西:
UPDATE OrderProcessing
SET orderTotalAmount = (orderSubtotal + tax) * (1 - discountAmount)
其次,我认为您的第一个查询中的括号过多。
您实际上可以使用某些函数将子查询返回的行限制为一行。
MYSQL:
SELECT column_name(s)
FROM table_name
LIMIT number;
甲骨文:
select *
from
( //your query here )
where ROWNUM = 1;
或者:
SELECT column_name(s)
FROM table_name
FETCH FIRST N ROWS;
希望对您有所帮助:)
我认为您不需要分组依据,但它应该类似于
UPDATE OrderProcessing o
SET orderTotalAmount =
(SELECT(SUM((orderSubtotal + tax) * (1 - discountAmount)))
FROM OrderProcessing
WHERE orderID = o.orderId)
否则,如错误所述,子查询 returns 多条记录。
DECLARE @orderTotal INT, @orderID int
SELECT @orderTotal = SUM((orderSubtotal+tax) * (1 - discountAmount))
FROM OrderProcessing
WHERE orderID = @orderID
GROUP BY orderID
UPDATE OrderProcessing
SET orderTotalAmount = @orderTotal
WHERE orderID = @orderID
如果我理解正确,您需要使用唯一值
更新 OrderProcessing table 中的许多行原始查询 returns 每个 orderID 一行。 之后您想要更新 orderTotalAmount,但您没有指定哪个 orderID。 显然,您希望以相同的方式更新所有订单。 为此,您需要 sfrutig 方法。 您需要在查询中指定您正在处理的 orderID,返回一行。 并循环使用它来更新所有订单。
由于我没有足够的积分,我无法将此评论放在 sfrutig 的解决方案旁边。