SQL - 分组进行列更新

时间:2012-12-25 08:11:33

标签: sql sql-server tsql sql-update

我正在使用AdvantureWorks数据库,但我在SalesOrderDetail表上没有实际销售值。该行应按订单ID包含LineTotal聚合。

我需要在每个订单ID行的“实际销售额”列中输入这些值:

select SUM(LineTotal) as ActualSales
from Sales.SalesOrderDetail
group by SalesOrderID

3 个答案:

答案 0 :(得分:0)

您需要将要分组的字段添加到查询中:

select SalesOrderID, sum(LineTotal) as ActualSales 
from SalesOrderDetail 
group by SalesOrderID

答案 1 :(得分:0)

UPDATE JOIN可以这样:

UPDATE od
SET od.ActualSalesColumn = g.ActualSales
FROM Sales.SalesOrderDetail od
INNER JOIN
(
    SELECT 
      SalesOrderDetail, 
      SUM(LineTotal) as ActualSales 
    FROM Sales.SalesOrderDetail 
    GROUP BY SalesOrderID
) g ON od.SalesOrderID = g.SalesOrderID;

或:使用CTE:

WITH ActualSales
AS
(
     SELECT 
       SalesOrderDetail, 
       SUM(LineTotal) as ActualSales 
     FROM Sales.SalesOrderDetail 
     GROUP BY SalesOrderID
)
UPDATE od
SET od.ActualSalesColumn = g.ActualSales
FROM Sales.SalesOrderDetail od
INNER JOIN ActualSales g ON od.SalesOrderID = g.SalesOrderID;

答案 2 :(得分:0)

UPDATE x
SET x.ActualSales = x.NewActualSales
FROM (
      SELECT ActualSales, SUM(LineTotal) OVER (PARTITION BY SalesOrderID) AS NewActualSales
      FROM Sales.SalesOrderDetail
      ) x