在多个分组上具有不同功能的SQL查询

时间:2013-12-02 19:27:13

标签: sql group-by sum group-concat

我试图将销售的某些商品的收入与这些商品的保修成本进行比较。我的代码看起来像:

SELECT DISTINCT od.orderID, pa.partID, pa.price AS revenue, wa.cost AS warcost, co.description AS wardesc
FROM orders od
LEFT OUTER JOIN parts pa ON pa.orderID = od.orderID
LEFT OUTER JOIN warranties wa ON pa.partID = wa.partID
LEFT OUTER JOIN malfunctions ml ON ml.malfID = wa.malfID
LEFT OUTER JOIN components co ON ml.compID = co.compID

返回类似下面的内容。

orderID  | partID | revenue |   warcost |   wardesc<br>
1   |   1001    | 100   |   45  |   Issue #1<br>
1   |   1001 |  100  | 50  | Issue #2<br>
1   |   1002 |  200  | 55    |  Issue #3<br>
2   |   1003 |  300  | 65    |  Issue #3<br>
2   |   1003 |  300  | 70    |  Issue #4

按订单分组,我想提取warcost,但只按个别partID的收入来计算,因此收入不计入两次。我发现这是不可能做到的!

最终结果应该如下,期待一些帮助!

orderID |   partID |        revenue |   warcost |   wardesc<br>
1 |     1001,1002    | 300   |  150  |  Issue #1, Issue #2, Issue #3<br>
2    |  1003     |  300  |  135  |  Issue #3, Issue #4

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT od.orderID,
  GROUP_CONCAT(pa.partID) AS parts,
  SUM(pa.price) AS revenue,
  SUM(wa.cost) AS warcost,
  GROUP_CONCAT(co.description) AS wardesc
FROM orders od
LEFT OUTER JOIN parts pa ON pa.orderID = od.orderID
LEFT OUTER JOIN warranties wa ON pa.partID = wa.partID
LEFT OUTER JOIN malfunctions ml ON ml.malfID = wa.malfID
LEFT OUTER JOIN components co ON ml.compID = co.compID
GROUP BY od.orderID

sqlfiddle demo (根据您的查询结果,这是对您所拥有的内容的简化)


编辑:

获取重复值可能是因为您可能在一个或多个连接中有多个匹配项。如果您发现无法删除重复项,并且原始查询的结果正确,则可以执行以下操作:

SELECT orderID,
  GROUP_CONCAT(partID),
  SUM(revenue),
  SUM(warcost),
  GROUP_CONCAT(wardesc)
FROM (
  SELECT DISTINCT od.orderID AS orderID,
    pa.partID AS partID,
    pa.price AS revenue,
    wa.cost AS warcost,
    co.description AS wardesc
  FROM orders od
  LEFT OUTER JOIN parts pa ON pa.orderID = od.orderID
  LEFT OUTER JOIN warranties wa ON pa.partID = wa.partID
  LEFT OUTER JOIN malfunctions ml ON ml.malfID = wa.malfID
  LEFT OUTER JOIN components co ON ml.compID = co.compID
  ) a
GROUP BY orderID