我正在尝试进行更新,这是我的查询
UPDATE t1
SET DOY = isnull(Sum(t2.Price),0)- isnull(Sum(t2.RestOfPrice),0)
FROM customermaster t1 INNER JOIN History t2
ON t1.CustomerID = t2.CustomerID
查询抛出错误
聚合可能不会出现在UPDATE语句的设置列表中。
答案 0 :(得分:2)
我认为以下内容可能会有所帮助:
UPDATE t1
SET t1.doy = t2.PriceDiff
FROM customermaster t1
INNER JOIN
( SELECT isnull(sum(Price),0)- isnull(sum(RestOfPrice),0) as PriceDiff, CustomerID
FROM History
GROUP BY CustomerID
) as t2
ON t1.CustomerID = t2.CustomerID;
答案 1 :(得分:2)
您需要使用子查询或CTE
使用子查询:
UPDATE t1
SET DOY = K.Res
FROM customermaster t1
INNER JOIN
(
SELECT T2.CustomerID,
ISNULL(SUM(t2.Price), 0) - ISNULL(SUM(t2.RestOfPrice), 0) Res
FROM History t2
GROUP BY T2.CustomerID
) K ON t1.CustomerID = K.CustomerID;
使用CTE:
WITH CTE AS
(
SELECT T.CustomerID,
ISNULL(SUM(T.Price), 0) - ISNULL(SUM(T.RestOfPrice), 0) Res
FROM History T
GROUP BY T.CustomerID
)
UPDATE customermaster
SET DOY = CTE.Res
WHERE CustomerID = CTE.CustomerID;
答案 2 :(得分:1)
您应该尝试这样的事情:
update customermaster
SET customermaster.DOY = final.result
from
(Select t1.CustomerID,(isnull(Sum(t2.Price),0)- isnull(Sum(t2.RestOfPrice),0))as result
from customermaster t1
INNER JOIN History t2
ON t1.CustomerID = t2.CustomerID) final
where customermaster.CustomerID=final.CustomerID
答案 3 :(得分:1)
这将回答您的问题
Create table #Customermaster
(CustomerID int,DOY Money)
Create table #History
(CustomerID int,Price Money,RestOfPrice money)
Insert into #Customermaster(CustomerID) Values (1),(2)
Insert into #History Values (1,100,50),(2,200,50),(1,300,50)
Select * from #Customermaster
Select * from #History
Update t1
Set T1.DOY = t2.D
From #Customermaster t1 join
(Select T2.CustomerID,isnull(Sum(t2.Price),0)- isnull(Sum(t2.RestOfPrice),0) as D
from #History T2 Join #Customermaster T1 On T1.CustomerID=T2.CustomerID Group By T2.CustomerID) t2
On T1.CustomerId=T2.CustomerID;
Select * from #Customermaster
Select * from #History
这是更新前的两个表
这是结果
希望对您有帮助