用UNION加入两个查询(每个查询都有不同的列)后,我只得到一列

时间:2018-11-17 07:51:35

标签: sql access ms-access-2016

我用UNION关键字加入了两个查询(Access 2016)。看起来像这样:

SELECT ITEM.IName, Sum(STOCK_IN.StockIn) AS SumOfIN
FROM ITEM INNER JOIN STOCK_IN ON ITEM.IName = STOCK_IN.IName
GROUP BY ITEM.IName
UNION SELECT ITEM.IName, Sum(STOCK_OUT.StockOut) AS SumOfOut
FROM ITEM INNER JOIN STOCK_OUT ON ITEM.IName = STOCK_OUT.IName
GROUP BY ITEM.IName

我得到以下结果:

IName | SumOfIN
----------------
Abis Nig | 3

Abrotanum | 1

Acid Acet | 2

Aconite  Nap |  2

Aconite  Nap |  3

Antim Crud |    3

Antim Tart |    1

但是我想要以下结果:

IName | SumOfIN | SumOfOut
----------------

Abis Nig | 3 | 0

Abrotanum | 1 | 0

Acid Acet | 2 | 0

Aconite  Nap | 2 | 3

Antim Crud | 0 | 3

Antim Tart | 0 | 1

任何人都可以告诉我在这里进行哪些更改吗?

2 个答案:

答案 0 :(得分:3)

您需要为正在UNION处理的表中不存在的第三列添加虚值。此外,您还需要一个整体SELECT / GROUP BY,因为您可以同时拥有StockIn和StockOut的值:

SELECT IName, SUM(SumOfIN), Sum(SumOfOut) 
FROM (SELECT ITEM.IName, Sum(STOCK_IN.StockIn) AS SumOfIN, 0 AS SumOfOut
      FROM ITEM INNER JOIN STOCK_IN ON ITEM.IName = STOCK_IN.IName
      GROUP BY ITEM.IName
      UNION ALL
      SELECT ITEM.IName, 0, Sum(STOCK_OUT.StockOut)
      FROM ITEM INNER JOIN STOCK_OUT ON ITEM.IName = STOCK_OUT.IName
      GROUP BY ITEM.IName) s
GROUP BY IName

请注意,结果表中的列名称全部取自UNION中的第一个表,因此我们必须在该查询中命名SumOfOut

答案 1 :(得分:1)

您完全不需要UNION即可执行以下查询:

select i.iname, si.sumofin, so.sumofout
from (item as i left join
      (select si.iname, sum(si.stockin) as sumofin
       from stock_in as si
       group by si.iname
      ) as si
      on si.iname = i.iname
     ) left join
     (select so.iname, sum(so.stockout) as sumofout
      from stock_out as so
      group by so.iname
     ) as so
     on so.iname = i.iname;

这将包括无库存或无库存的项目。那可能是好事,也可能是坏事。如果不好,请添加:

where si.sumofin > 0 or so.sumofout > 0

如果您要使用union all,则可以完全不用join来取代物品:

SELECT IName, SUM(SumOfIN), Sum(SumOfOut) 
FROM (SELECT si.IName, Sum(si.StockIn) AS SumOfIN, 0 AS SumOfOut
      FROM STOCK_IN as si
      GROUP BY si.INAME
      UNION ALL
      SELECT so.IName, 0, Sum(so.StockOut)
      STOCK_OUT so 
      GROUP BY so.IName
     ) s
GROUP BY IName;

仅当您的库存项目不在JOIN表中时,items才是必需的。那可能是不良的数据建模的迹象。