2

我在玩AdvantureWorksDB,但我没有实际销售额值SalesOrderDetail。此行应该包含LineTotal按订单 ID 的聚合。

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

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

3 回答 3

0

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

select SalesOrderID, sum(LineTotal) as ActualSales 
from SalesOrderDetail 
group by SalesOrderID
于 2012-12-25T08:14:11.933 回答
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;
于 2012-12-25T08:21:08.863 回答
0
UPDATE x
SET x.ActualSales = x.NewActualSales
FROM (
      SELECT ActualSales, SUM(LineTotal) OVER (PARTITION BY SalesOrderID) AS NewActualSales
      FROM Sales.SalesOrderDetail
      ) x
于 2012-12-25T10:19:09.447 回答