3

现在我有 3 张桌子

订单:

身份证 | 日期 | 机器 | 规划

好片:

身份证 | 日期 | 机器 | 件 | 产品

坏片:

身份证 | 日期 | 机器 | 件 | 产品 | 零件

查询的输出是

日期 | 机器 | 规划 | 好片| 坏件

实际的查询是这样的:

SELECT
  data.Date AS Date,
  data.Machine AS Machine,
  SUM(CASE WHEN data.type = 'Planning' THEN data.value END ) AS Planning,
  SUM(CASE WHEN data.type = 'GoodPieces' THEN data.value END ) AS GoodPieces,
  SUM(CASE WHEN data.type = 'BadPieces' THEN data.value END ) AS BadPieces
FROM
      ( SELECT
          'Planning' AS Type,
          Date AS Date,
          Machine AS Machine,
          Planning AS Value
        FROM Orders
        UNION ALL
        SELECT
          'GoodPieces',
          Date,
          Machine,
          Pieces AS Value
        FROM GoodPieces
        UNION ALL
        SELECT
          'BadPieces'
          Date,
          Machine,
          Pieces AS Value
        FROM BadPieces ) AS data
GROUP BY
   Date,
   Machine

我的问题是是否有办法用这 3 个表获得相同的输出

订单:

身份证 | 日期 | 机器| 规划

好片:

订单号 | 件 | 产品

坏片:

订单号 | 件 | 产品 | 零件

谢谢,

4

1 回答 1

5

当然,只是LEFT JOIN在表格中并总结适当的列:

SELECT
  O.Date,
  O.Machine,
  SUM(COALESCE(O.Planning, 0)) AS Planning,
  SUM(COALESCE(G.Pieces, 0)) AS GoodPieces,
  SUM(COALESCE(B.Pieces, 0)) AS BadPieces
FROM
  Orders O
LEFT JOIN
  (SELECT G.OrderID,
     SUM(COALESCE(G.Pieces, 0)) AS GoodPieces
   FROM GoodPieces G
   GROUP BY G.OrderID) G ON G.OrderID = O.ID
LEFT JOIN
  (SELECT B.OrderID,
     SUM(COALESCE(B.Pieces, 0)) AS BadPieces
   FROM BadPieces B
   GROUP BY B.OrderID) B ON B.OrderID = O.ID
GROUP BY
  O.Date,
  O.Machine;

演示:http ://www.sqlfiddle.com/#!3/09a73/17

编辑:更新以处理@MikaelEriksson评论中给出的点。

于 2012-04-14T21:28:50.777 回答