如何使用MSSQL中的聚合函数更新表中的两列?

时间:2015-06-04 10:05:25

标签: sql sql-server sql-update aggregate-functions

我尝试了几种选择,但我找不到合适的解决方案。 我想更新Products表中的两列。 需要从另一个名为ProductShops的表中更新这些列。

这两列名为LowestPriceLowestPriceShopId。 因此,我需要来自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

3 个答案:

答案 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