Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Statement using Join and Group By

I have written the below Update Statement, but it shows the error such as "Incorrect syntax near the keyword 'GROUP'."

UPDATE         J SET         J.StatusID = CASE WHEN SUM(DUV.VendorDUQuantity) = SUM(RD.InvoiceQuantity) THEN 1 ELSE J.StatusID END FROM         PLN_DU_Vendor DUV     INNER JOIN ENG_Release R ON R.ReleaseID = DUV.ReleaseID     INNER JOIN ENG_DU_Header H ON H.ReleaseID = R.ReleaseID AND DUV.DUID = H.DUID     INNER JOIN MKT_JobOrder J ON J.JobOrderID = R.JobOrderID     INNER JOIN MKT_CustomerOrder CO ON CO.OrderID = J.OrderID     LEFT JOIN PMT_RFDHeader RH ON RH.JobOrderID = J.JobOrderID     LEFT JOIN PMT_RFDDetail RD ON RD.RFDID = RH.RFDID AND RD.DUID = DUV.DUID                  WHERE          CO.OrderID = 100 GROUP BY          J.JobOrderID 

Instead of Update, Select is working perfectly for the above Query. What would be the problem and How to write the Query based on Join and Group By clause.

like image 858
thevan Avatar asked Sep 01 '12 07:09

thevan


People also ask

Can you use group by in update statement?

As of my knowledge, No you can not directly use GROUP by as you can not use aggregate functions in an UPDATE query.

Can we use update in join?

SQL UPDATE JOIN could be used to update one table using another table and join condition.

Can we use group by and join together?

SQL Inner Join permits us to use Group by clause along with aggregate functions to group the result set by one or more columns. Group by works conventionally with Inner Join on the final result returned after joining two or more tables.

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

In SQL Server, we can join two or more tables, but we cannot update the data of multiple tables in a single UPDATE statement.


1 Answers

You can try putting the group by inside of a subquery, then join by the "JobOrderID", like this:

UPDATE J SET J.StatusID = A.statusId FROM MKT_JobOrder J INNER JOIN (     SELECT J.JobOrderID         , CASE              WHEN SUM(DUV.VendorDUQuantity) = SUM(RD.InvoiceQuantity)                 THEN 1             ELSE J.StatusID             END AS statusId      FROM PLN_DU_Vendor DUV     INNER JOIN ENG_Release R ON R.ReleaseID = DUV.ReleaseID     INNER JOIN ENG_DU_Header H ON H.ReleaseID = R.ReleaseID                                AND DUV.DUID = H.DUID     INNER JOIN MKT_JobOrder J ON J.JobOrderID = R.JobOrderID     INNER JOIN MKT_CustomerOrder CO ON CO.OrderID = J.OrderID     LEFT JOIN PMT_RFDHeader RH ON RH.JobOrderID = J.JobOrderID     LEFT JOIN PMT_RFDDetail RD ON RD.RFDID = RH.RFDID                                AND RD.DUID = DUV.DUID     WHERE CO.OrderID = 100     GROUP BY J.JobOrderID            , J.StatusID     ) A ON J.JobOrderID = A.JobOrderID 
like image 154
hgulyan Avatar answered Sep 29 '22 20:09

hgulyan