0

如果子查询中的另一个值小于某个值或 null,我正在尝试更新列:

UPDATE
    Customer
SET
    PriceClassID = 'A'
FROM
    (
    SELECT
        custid,
        SUM(curybaldue) as last_sum
    FROM
        SOShipHeader
    WHERE
        OrdDate > @year_ago
        AND
        Status = 'C'
    GROUP BY
        CustID
    ) a 
    JOIN Customer ON Customer.CustId = a.CustId
    WHERE
        ( last_sum < 3000 OR last_sum IS NULL )
        AND
        PriceClassID IN ('CLUB', 'CLUB-E')
        AND
        Customer.User7 <= @year_ago
        AND
        Customer.User7 > @year_and_month_ago

但是,当我检查是否PriceClassID已更改时,我发现 last_sum 为空的任何行都没有更改。我究竟做错了什么?

4

1 回答 1

0

您是否期望last_sum为 null
(1) 因为curybaldue为 null,或者(2) 因为 ,中
没有行?SOShipHeadercust-id

如果是 (1),那么您的问题就出在其他地方:对于cust-id具有任何非空值的a curybaldueSUM将成功计算,将这些空值计为零。对于所有为空的 a,cust-id将为空,并由您的. curybalduelast_sumWHERE

如果是 (2) - 您的代码将删除空值。在这种情况下,请执行以下操作:
(A) 将Customer表设为您的FROM表,并且
(B) 使用LEFT OUTER JOIN, 使其成为可选链接(因为JOIN默认为INNER JOIN,删除所有CustomerJOIN为 的行SOShipHeader):

UPDATE
    Customer
SET
    PriceClassID = 'A'
FROM 
    Customer 
  LEFT OUTER JOIN 
    (
    SELECT
        custid,
        SUM(curybaldue) as last_sum
    FROM
        SOShipHeader
    WHERE
        OrdDate > @year_ago
        AND
        Status = 'C'
    GROUP BY
        CustID
    ) a 
          ON Customer.CustId = a.CustId
    WHERE
        ( last_sum < 3000 OR last_sum IS NULL )
        AND
        PriceClassID IN ('CLUB', 'CLUB-E')
        AND
        Customer.User7 <= @year_ago
        AND
        Customer.User7 > @year_and_month_ago
于 2013-11-07T01:25:27.457 回答