将两个选择查询的结果合并到一个表中

时间:2019-11-14 16:22:39

标签: sql ms-access

我有以下两个表:

STOCK_ON_HAND:这显示了我手头上的所有库存 STOCK_ON_ORDER:这向我显示了我所订购的所有库存

我有以下两个查询来汇总表:

SELECT STOCK_CODE, SUM(QTY)
FROM STOCK_ON_HAND
GROUP BY STOCK_CODE
HAVING SUM(QTY) <>0;

SELECT STOCK_CODE, SUM(ON_ORDER)
FROM STOCK_ON_ORDER
GROUP BY STOCK_CODE
HAVING SUM(STOCK_ON_ORDER) <>0;

我基本上想将上述内容与一个表合并显示以下字段:

  • STOCK_CODE
  • STOCK_ON_HAND
  • STOCK_ON_ORDER

实现此目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

为此,您需要一个FULL OUTER JOIN,Access不直接支持它,但是您可以使用UNION模拟它,如下所示:

SELECT h.STOCK_CODE, h.HQTY AS STOCK_ON_HAND, o.OQTY AS STOCK_ON_ORDER
FROM (
  SELECT STOCK_CODE, SUM(QTY) AS HQTY
  FROM STOCK_ON_HAND
  GROUP BY STOCK_CODE
  HAVING SUM(QTY) <> 0
) h LEFT JOIN (
  SELECT STOCK_CODE, SUM(ON_ORDER) AS OQTY
  FROM STOCK_ON_ORDER
  GROUP BY STOCK_CODE
  HAVING SUM(ON_ORDER) <> 0
) o ON o.STOCK_CODE = h.STOCK_CODE
UNION
SELECT o.STOCK_CODE, h.HQTY AS STOCK_ON_HAND, o.OQTY AS STOCK_ON_ORDER
FROM (
  SELECT STOCK_CODE, SUM(QTY) AS HQTY
  FROM STOCK_ON_HAND
  GROUP BY STOCK_CODE
  HAVING SUM(QTY) <> 0
) h RIGHT JOIN (
  SELECT STOCK_CODE, SUM(ON_ORDER) AS OQTY
  FROM STOCK_ON_ORDER
  GROUP BY STOCK_CODE
  HAVING SUM(ON_ORDER) <> 0
) o ON o.STOCK_CODE = h.STOCK_CODE

如果您不想在结果中看到null(如果存在),而是将它们替换为0,请使用函数Nz(),如下所示:

SELECT h.STOCK_CODE, Nz(h.HQTY, 0) AS STOCK_ON_HAND, Nz(o.HQTY, 0) AS STOCK_ON_ORDER


或从两个表中获取不同的STOCK_CODE,然后LEFT JOIN到每个表中:

SELECT c.STOCK_CODE, h.HQTY AS STOCK_ON_HAND, o.OQTY AS STOCK_ON_ORDER
FROM ((
  SELECT STOCK_CODE FROM STOCK_ON_HAND
  UNION
  SELECT STOCK_CODE FROM STOCK_ON_ORDER
) AS c LEFT JOIN (
  SELECT STOCK_CODE, SUM(QTY) AS HQTY
  FROM STOCK_ON_HAND
  GROUP BY STOCK_CODE
  HAVING SUM(QTY) <> 0
) h ON h.STOCK_CODE = c.STOCK_CODE )
LEFT JOIN (
  SELECT STOCK_CODE, SUM(ON_ORDER) AS OQTY
  FROM STOCK_ON_ORDER
  GROUP BY STOCK_CODE
  HAVING SUM(ON_ORDER) <> 0
) o ON o.STOCK_CODE = c.STOCK_CODE

答案 1 :(得分:1)

我建议在汇总之前先做UNION ALL

SELECT STOCK_CODE, SUM(on_hand), SUM(on_order)
FROM (SELECT STOCK_CODE, SUM(QTY) as on_hand, 0 on_order
      FROM STOCK_ON_HAND
      GROUP BY STOCK_CODE
      UNION ALL
      SELECT STOCK_CODE, 0, SUM(ON_ORDER) as on_order
      FROM STOCK_ON_ORDER
      GROUP BY STOCK_CODE
     ) s
GROUP BY STOCK_CODE
HAVING on_hand <> 0 OR on_order <> 0;

如果MS Access在UNION ALL子句中不支持FROM,则可以使用视图进行设置。