使用 Join 和 Group By 更新语句

Posted

技术标签:

【中文标题】使用 Join 和 Group By 更新语句【英文标题】:Update Statement using Join and Group By 【发布时间】:2012-08-26 21:12:34 【问题描述】:

我已经写了下面的更新语句,但是它显示了诸如“关键字'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 不是更新,而是完美地适用于上述查询。会出现什么问题以及如何编写基于 Join 和 Group By 子句的查询。

【问题讨论】:

【参考方案1】:

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

【讨论】:

【参考方案2】:

用户子查询改为执行此操作

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

【讨论】:

您的查询无效。 JobOrderId 有两个列,您应该指定它应该使用哪一个。

以上是关于使用 Join 和 Group By 更新语句的主要内容,如果未能解决你的问题,请参考以下文章

sql语句中 group by用法

join ,group by

mysql ORDER BY,GROUP BY 和DISTINCT原理

在 Django 模型上执行 INNER JOIN、GROUP BY 和 COUNT

SQL语句中,为啥where子句不能使用列别名,而order by却可以?

SQL语句的执行顺序怎么理解,特别是ORDER BY子句怎么理解?