子查询返回的值超过1。当子查询遵循!=,<,<=,>,> =时,不允许这样做

时间:2018-11-25 16:55:26

标签: sql-server

我正在尝试更新字段,以便销售量大于0的客户的CustomerLevel处于“级别1”,但这对我不起作用:

UPDATE Customers 
    SET CustomerLevel = 'Level 1' 
WHERE (
       (SELECT SUM(Sales.Subtotal)
        FROM Sales 
        JOIN Customers
        ON Customers.CustomerID = Sales.CustomerID
        GROUP BY Customers.CustomerID
       )
>=0) 

2 个答案:

答案 0 :(得分:0)

您的子查询将返回{{1}的每个记录的所有客户ID的销售小计(因为您正在引用子查询中的customers表的另一个实例) } customers查询中的表。

您应该改为使用相关子查询,该子查询引用要更新的当前记录的UPDATE,即:

customerid

答案 1 :(得分:0)

几种方法可以做到这一点。推测,但这可能是最佳的执行计划,但请检查一下。

UPDATE Customers 
    SET CustomerLevel = 'Level 1' 
FROM Customers AS c1
INNER JOIN
       (SELECT 
            SUM(Sales.Subtotal) AS sum2, 
            s2.CustomerID AS CustomerID2
        FROM Sales AS s2
        GROUP BY s2.CustomerID
       ) AS t2
ON t2.CustomerID = c1.CustomerID 
   AND t2.sum2 >=0