我正在使用AdvantureWorks
数据库,但我在SalesOrderDetail
表上没有实际销售值。该行应按订单ID包含LineTotal
聚合。
我需要在每个订单ID行的“实际销售额”列中输入这些值:
select SUM(LineTotal) as ActualSales
from Sales.SalesOrderDetail
group by SalesOrderID
答案 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