1

我有 2 个遇到问题的代码。我看了一些其他的答案,但完全糊涂了。这是SQL代码..(它是一个Access,SQL pass thru query)

UPDATE    TOP (500) InventorySuppliers
SET              BoydQuantityAvailable = SUM(Boyd0004Daily.QOH), Cost = Boyd0004Daily.Cost
FROM         Boyd0004Daily INNER JOIN
                      InventorySuppliers ON Boyd0004Daily.LocalSKU = InventorySuppliers.LocalSKU
WHERE     (InventorySuppliers.SupplierID = 4) AND (NOT (InventorySuppliers.BoydQuantityAvailable = SUM(Boyd0004Daily.QOH))) OR
                      (InventorySuppliers.SupplierID = 4) AND (NOT (InventorySuppliers.Cost = Boyd0004Daily.Cost))

它不喜欢 SUM(Boyd0004Daily.QOH) 上的更新,但在我的一生中,我无法弄清楚如何重写它,所以它进行选择,然后使用 1 个查询进行更新。

4

2 回答 2

1

您缺少一个group by. 任何时候使用聚合函数时,都必须包含一个分组依据,该分组依据包含所有未聚合的列。

你也在SUM你的WHERE子句中使用它不起作用。当您想根据聚合过滤结果时,您必须HAVING改用。

于 2013-02-20T19:01:08.880 回答
0

您要做的第一件事是让选择正确:

select *
from InventorySuppliers i
inner join (select LocalSKU, SUM(QOH) QOH_SUM, MAX(Cost) Cost --max or min
            from Boyd0004Daily
            group by LocalSKU) a 
        on a.LocalSKU = i.LocalSKU
where i.SupplierID = 4
and ((i.BoydQuantityAvailable != a.QOH_SUM))
    OR i.Cost != a.Cost))

然后将您的选择转换为更新:

update i
set i.BoydQuantityAvailable = a.QOH_SUM,
    i.Cost = a.Cost
from InventorySuppliers i
inner join (select LocalSKU, SUM(QOH) QOH_SUM, MAX(Cost) Cost --max or min
            from Boyd0004Daily
            group by LocalSKU) a 
        on a.LocalSKU = i.LocalSKU
where i.SupplierID = 4
    and ((i.BoydQuantityAvailable != a.QOH_SUM))
        OR i.Cost != a.Cost))

我认为这个查询应该适合你。我可能有错误,因为我无法测试您的数据。

于 2013-02-20T19:29:52.033 回答