I'm trying to make an update, and here is my query
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
The query throw an error
An aggregate may not appear in the set list of an UPDATE statement.
SQL UPDATE JOIN could be used to update one table using another table and join condition. UPDATE tablename INNER JOIN tablename ON tablename. columnname = tablename.
In SQL Server, you can use these join clauses in the UPDATE statement to perform a cross-table update. In this syntax: First, specify the name of the table (t1) that you want to update in the UPDATE clause. Next, specify the new value for each column of the updated table.
Multiple-table UPDATE statements can use any type of join allowed in SELECT statements, such as LEFT JOIN.
In SQL, there is a requirement of a single query/statement to simultaneously perform 2 tasks at the same time. For instance, updating 2 different tables together in a single query/statement. This involves the use of the BEGIN TRANSACTION clause and the COMMIT clause.
You need to use a subquery or a CTE
Using a SubQuery:
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;
Using a 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;
I think the following may help :
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;
You should try something like this:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With