在UPDATE命令中聚合

时间:2013-12-10 14:50:39

标签: sql-server-2008

我正在尝试根据最早的发票更新所有客户的付款条件。到目前为止,我有以下代码:

UPDATE [CUSTOMERS - Main]
SET    Payterms = 0
FROM   (SELECT Max(INVOICES.InvoiceDate) AS LastInvoice,
               Datediff(day, Max(INVOICES.InvoiceDate), Getdate()) AS age,
               INVOICES.CompanyName,
               [CUSTOMERS - Main].PayTerms,
               [CUSTOMERS - Main].CreditLimit,
               [CUSTOMERS - Main].CompanyRegNo
        FROM   INVOICES
               INNER JOIN [CUSTOMERS - Main]
                       ON INVOICES.CompanyName = [CUSTOMERS - Main].CompanyName
        GROUP  BY INVOICES.CompanyName,[CUSTOMERS - Main].PayTerms,[CUSTOMERS - Main].CreditLimit,[CUSTOMERS - Main].CompanyRegNo
        HAVING (Datediff(day, Max(INVOICES.InvoiceDate), Getdate()) > 365)
               AND ([CUSTOMERS - Main].PayTerms > 0
                     OR [CUSTOMERS - Main].CreditLimit > 0))

但它不起作用。如何更新具有聚合函数的查询?

1 个答案:

答案 0 :(得分:2)

这似乎是一个更加整洁的方法,尽管我可能会在一天之内离开你的实际意图,例如:今天是12月10日,您是否希望使用比去年12月10日或12月11日更新的发票排除客户?这不包括发票比12月10日更新的客户。

DECLARE @cutoff DATE = DATEADD(DAY, -365, GETDATE());

UPDATE c SET Payterms = 0
  FROM dbo.[CUSTOMERS - Main] AS c
  WHERE (c.PayTerms > 0 OR c.CreditLimit > 0)
  AND NOT EXISTS
  (
    SELECT 1 FROM dbo.INVOICES AS i
      WHERE i.CompanyName = c.CompanyName
      AND InvoiceDate >= @cutoff
  );