我在玩AdvantureWorks
DB,但我没有实际销售额值SalesOrderDetail
。此行应该包含LineTotal
按订单 ID 的聚合。
我需要将这些值输入到每个订单 ID 行的实际销售额列中:
select SUM(LineTotal) as ActualSales
from Sales.SalesOrderDetail
group by SalesOrderID
我在玩AdvantureWorks
DB,但我没有实际销售额值SalesOrderDetail
。此行应该包含LineTotal
按订单 ID 的聚合。
我需要将这些值输入到每个订单 ID 行的实际销售额列中:
select SUM(LineTotal) as ActualSales
from Sales.SalesOrderDetail
group by SalesOrderID
您需要将要分组的字段添加到查询中:
select SalesOrderID, sum(LineTotal) as ActualSales
from SalesOrderDetail
group by SalesOrderID
你可以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;
UPDATE x
SET x.ActualSales = x.NewActualSales
FROM (
SELECT ActualSales, SUM(LineTotal) OVER (PARTITION BY SalesOrderID) AS NewActualSales
FROM Sales.SalesOrderDetail
) x