使用Join和Group By更新语句

时间:2012-09-01 07:09:14

标签: sql sql-server-2008 join group-by 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,而是完美适用于上述Query。会出现什么问题以及如何基于Join和Group By子句编写查询。

2 个答案:

答案 0 :(得分:29)

您可以尝试将组放在子查询中,然后通过“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

答案 1 :(得分:3)

用户子查询代替执行此操作

UPDATE 
   J
 SET StatusID = x.Status
   FROM 
   (select CASE WHEN SUM(DUV.VendorDUQuantity) = SUM(RD.InvoiceQuantity) THEN 1 
    ELSE   J.StatusID END as Status 
     JobOrderID
     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) X
 INNER JOIN MKT_JobOrder J On x.JobOrderID = J.JobOrderID