在 Northwinds 中,我如何编写脚本来更改订购数量超过 50 的所有订单的“订单详细信息”表中的折扣并显示给定的最大折扣。
在北风表中,我使用 MAX 还是 SUM?假设影响 159 行。我有这个,但不断收到错误。
SELECT OrderID, ProductID,UnitPrice,Quantity,
MAX (Discount)
FROM [Order Details]
如果您想查看所有这些列以及最大折扣,那么我建议您使用 Over partition by,因为您可以返回聚合,而无需按您选择的所有列进行分组。
SELECT OrderID,ProductID,UnitPrice,Quantity,
MAX(Discount) OVER(PARTITION BY OrderID) as MaxDiscount
from Order Details
至于超过 50 的数量,我会使用
SELECT OrderID,ProductID,UnitPrice,Quantity,Discount
FROM Order Details
where Quantity > 50
问题的原因是数据库不知道如何向您显示 OrderID、ProductID、UnitPrice、Quantity 并且仍然为您提供 Discount 的最大值。
当您使用聚合函数时,它要求您按某些字段进行分组。
例如:
SELECT OrderID, ProductID,UnitPrice,Quantity, MAX (Discount)
FROM [Order Details]
group by OrderID, ProductID,UnitPrice,Quantity
为了获得超过 50 个的订单数量,您需要使用HAVING
关键字。
SELECT OrderID, ProductID,UnitPrice,Quantity,Discount
FROM [Order Details]
having Quantity > 50