小编典典

使用Join和Group By更新语句

sql

我已经写了下面的Update Statement,但是它显示了诸如“关键字’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

对于上面的查询,Select代替Update可以完美地工作。这将是什么问题,以及如何基于Join和Group By子句编写查询。


阅读 180

收藏
2021-03-17

共1个答案

小编典典

您可以尝试将组放在子查询的内部,然后通过“ JobOrderID”加入,如下所示:

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
2021-03-17