Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make update using join

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.

like image 523
Dim Avatar asked Oct 20 '18 17:10

Dim


People also ask

Can you do an UPDATE with a join?

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.

Can we use join in UPDATE SQL?

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.

Can we use left join in UPDATE query?

Multiple-table UPDATE statements can use any type of join allowed in SELECT statements, such as LEFT JOIN.

Can you UPDATE 2 tables with a UPDATE statement in SQL?

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.


3 Answers

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;
like image 178
Ilyes Avatar answered Sep 23 '22 03:09

Ilyes


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;
like image 42
Barbaros Özhan Avatar answered Sep 23 '22 03:09

Barbaros Özhan


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
like image 35
Helgato Avatar answered Sep 21 '22 03:09

Helgato