我该如何使用SELECT查询中同一张表的2倍来更新SQL中的列?

时间:2018-07-05 23:04:11

标签: sql sql-server-2008

这里的情况是,我有一个非常复杂的查询,该查询生成的表只有两列,一列是某位雇员销售的产品总数的列,另一列是该雇员的ID,我想做的是使用此表更新雇员的N_products列(已售产品数量)。已经运行的查询是:

SELECT 
    SUM(QUANTITY) AS productosven, 
    EmployeeID 
FROM 
    (SELECT 
         Orders.OrderID, Orders.EmployeeID, [Order Details].Quantity 
     FROM 
         Orders  
     INNER JOIN 
         DimEmployee ON Orders.EmployeeID = DimEmployee.EmployeeID 
     INNER JOIN 
         [Order Details] ON [Order Details].OrderID = Orders.OrderID)
     GROUP BY 
         EmployeeId) x

它生成的表是:

enter image description here

我要实现的查询是:

UPDATE DimEmployee 
SET N_Products = (SELECT SUM(QUANTITY) AS productosven 
                  FROM
                      (SELECT 
                           Orders.OrderID, Orders.EmployeeID, [Order Details].Quantity 
                       FROM 
                           Orders  
                       INNER JOIN 
                           DimEmployee ON Orders.EmployeeID = DimEmployee.EmployeeID 
                       INNER JOIN 
                           [Order Details] ON [Order Details].OrderID = Orders.OrderID) AS X
                  GROUP BY EmployeeId)
WHERE 
    EmployeeID = (SELECT EmployeeID 
                  FROM
                      (SELECT 
                           Orders.OrderID, Orders.EmployeeID, [Order Details].Quantity 
                       FROM 
                           Orders  
                       INNER JOIN 
                           DimEmployee ON Orders.EmployeeID = DimEmployee.EmployeeID 
                       INNER JOIN 
                           [Order Details] ON [Order Details].OrderID = Orders.OrderID) AS X 
                  GROUP BY EmployeeId)

基本上,我尝试两次使用SELECT查询,第一次是获取产品并将其存储在N_products中,第二次是将其与相同的查询,但是SQL Server生成错误:

  

男人。 512,第16层,状态1,第1行
  子查询返回了多个值,当它在=,之后时是不正确的! =,<,<=,>,> =或用作表达式时。

2 个答案:

答案 0 :(得分:1)

您可以在JOIN中使用UPDATE。所以我建议:

UPDATE e
    SET n_products = sum_quantity
FROM DimEmployee e JOIN
     (SELECT o.EmployeeID, SUM(Quantity) as sum_quantity
      FROM Orders o JOIN
           [Order Details] od
           ON od.OrderID = o.OrderID
      GROUP BY o.EmployeeID
     ) o
     ON o.EmployeeID = e.EmployeeID;

请注意,如果没有员工订单,这不会更新该字段(这似乎是您查询的目的)。如果您确实希望在这种情况下也进行更新,则可以使用LEFT JOIN

答案 1 :(得分:0)

这个怎么样?

UPDATE DimEmployee
SET N_Products = (
    SELECT sum(od.Quantity) 
    FROM Orders o INNER JOIN [Order Details] od ON od.OrderID = Orders.OrderID
    WHERE o.EmployeeID = DimEmployee.EmployeeID
);