select a.商品id,sum(a.数量) as 入库数量,sum(b.数量) as 出库数量,(sum(a.数量)-sum(b.数量)) as 库存,a.日期 from 入库表 a,出库表 b where a.商品id=b.商品id group by a.商品id,a.日期 order by a.商品id,a.日期
当然不对了,两表的ID都不是唯一的,所以联表后会出现重复的记录。
应该让两表的ID与日期成联合主键时再连接:select A.商品ID,入库数量=A.数量,出库数量=B.数量,库存=A.数量-B.数量,A.日期
from
(select 商品ID,日期,数量=sum(数量) from 入库表 group by 商品ID,日期) A, (select 商品ID,日期,数量=sum(数量) from 出库表 group by 商品ID,日期) B where A.商品ID=B.商品ID and A.日期=B.日期
select a.商品idas 商品ID,sum(a.数量) as 入库数量,sum(b.数量) as 出库数量,sum(a.数量)-sum(b.数量))as 库存,a.日期 as 日期 from ((select*from A group by 商品ID)as aright join(select*from B group by 商品ID) as b on a.商品id=b.商品id and a.日期=b.日期 )order by 日期