日期:2014-05-17  浏览次数:20823 次

关于联合查询求库存问题
有2个表入库表和出库表

我想用联合查询计算库存
sql语句为 SELECT ,编号,入库编号,日期,材料名称,型号规格,计量单位,调入单位,收料人,入库数量,0 as 出库数量 from 入库表
UNION ALL select 编号,出库编号,日期,材料名称,型号规格,计量单位,调出单位,领料人,0 as 入库数量,出库数量 from 出库表  
但是这样却无法计算“库存数量”,联合查询可以显示出来,但是库存数量的sql语句怎么写 
我以前用access的时候是这样写的 SELECT 报表联合.物资类别, 报表联合.编号, 报表联合.入库编号 AS 出入库编号, 报表联合.日期, 报表联合.材料名称, 报表联合.型号规格, 报表联合.计量单位, 报表联合.调入单位 AS 出入库单位, 报表联合.收料人 AS 收发料人, 报表联合.入库数量, 报表联合.出库数量, nz(DSum("[入库数量]","报表联合","编号='" & [编号] & "'and [型号规格] = '" & [型号规格] & "'and [型号规格] = '" & [型号规格] & "'and 日期<=#" & [日期] & "#"))-nz(DSum("[出库数量]","报表联合","编号='" & [编号] & "'and [材料名称] = '" & [材料名称] & "'and [型号规格] = '" & [型号规格] & "'and 日期<=#" & [日期] & "#")) AS 结存数量
FROM 报表联合
ORDER BY 报表联合.日期, 报表联合.材料名称
请哪位高手帮忙

------解决方案--------------------
你要实现什么样的效果,就是实时计算当前各产品的实际库存里吗?如果这样的话可以这样写SQL语句
SQL code

select A.材料编号,(select sum(入库数量) from 入库表 where 材料编号=A.材料编号) as 入库,
(select sum(出库数量) from 出库表 where 材料编号=A.材料编号)  as 出库,
(入库-出库) as 库存 
 from (select 材料编号 from 入库表 group by 材料编号) as A