我尝试了几种选择,但我找不到合适的解决方案。
我想更新Products
表中的两列。
需要从另一个名为ProductShops
的表中更新这些列。
这两列名为LowestPrice
和LowestPriceShopId
。
因此,我需要来自NewPrice + DeliveryCosts
中的总和ProductShops
和来自该记录的ShopId
的最低值。
需要在Products
表中进行更新。
我尝试过的事情是:
UPDATE Products
SET LowestPrice = MIN(ps.NewPrice + ps.DeliveryCosts),
LowestPriceShopId = ps.ShopId
FROM Products
INNER JOIN ProductShops ps ON Products.Id = ps.ProductId
错误消息:聚合可能不会出现在UPDATE语句的集合列表中。
UPDATE p
SET LowestPrice = ps2.totalPrice,
LowestPriceShopId = ps2.ShopId
FROM Products p JOIN
(select ps.ProductId, MIN(ps.NewPrice + ps.DeliveryCosts) AS totalPrice, ShopId FROM ProductShops ps) ps2
ON p.Id = ps2.ProductId
错误消息:列'ProductShops.ProductId'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
UPDATE Products
SET LowestPrice = (SELECT MIN(ps.NewPrice + ps.DeliveryCosts)
FROM ProductShops ps WHERE ps.ProductId = p.Id)
FROM Products p
使用上一个查询,我不知道如何获取ShopId
。
答案 0 :(得分:3)
UPDATE p
SET LowestPrice = ps2.totalPrice,
LowestPriceShopId = ps2.ShopId
FROM Products p
JOIN (SELECT
ps.ProductId,
MIN(ps.NewPrice + ps.DeliveryCosts) AS totalPrice,
ShopId
FROM ProductShops ps
GROUP BY ps.ProductId,ShopId) ps2
ON p.Id = ps2.ProductId
答案 1 :(得分:2)
我找到了正确的解决方案:
UPDATE p
SET LowestPrice = ps3.totalPrice,
LowestPriceShopId = ps3.ShopId
FROM Products p
JOIN
(
SELECT ps1.ProductId, ps1.NewPrice + ps1.DeliveryCosts as totalPrice, ps1.ShopId FROM ProductShops ps1
LEFT JOIN ProductShops ps2
ON ps1.ProductId = ps2.ProductId AND (ps1.NewPrice + ps1.DeliveryCosts) > (ps2.NewPrice + ps2.DeliveryCosts)
WHERE ps2.NewPrice is NULL AND ps2.DeliveryCosts is NULL
) ps3
ON p.Id = ps3.ProductId
答案 2 :(得分:1)
您需要char
:
GROUP BY
同时UPDATE p
SET LowestPrice = ps2.totalPrice,
LowestPriceShopId = ps2.ShopId
FROM Products p
JOIN
(
select
ps.ProductId,
MIN(ps.NewPrice)+MIN(ps.DeliveryCosts) AS totalPrice,
ShopId
FROM
ProductShops ps
GROUP BY
ps.ProductId,
ps.ShopId
) ps2
ON p.Id = ps2.ProductId
和ProductId