可以做update触发器或者用前台程序控制!

解决方案 »

  1.   

    select *,(select top 1 出库数量 as 最后一次出库数量 
              from table_in where 货物名 = B.货物名 order by 出库时间 desc),
             (select top 1 入库数量 as 最后一次入库数量 
              from table_out where 货物名 = B.货物名 order by 入库时间 desc) from
    (select A.货物名,sum(A.入库数量) as 库存数量 from
    (select 货物名,入库数量,入库时间 from table_out union all
     select 货物名,-1*出库数量,出库时间 from table_in) A
     group by A.货物名) B
      

  2.   

    select *
      ,最后一次出库数量=(select top 1 出库数量 from table_out where 货物名=a.货物名 order by 出库时间 desc)
      ,最后一次入库数量=(select top 1 入库数量 from table_in where 货物名=a.货物名 order by 入库时间 desc)
    from(
    select 货物名=isnull(a.货物名,b.货物名)
      ,库存数量=sum(isnull(a.入库数量,0)-isnull(b.出库数量,0))
    from table_in a full join table_out on a.货物名=b.货物名
    group by isnull(a.货物名,b.货物名)
    ) a
      

  3.   

    生成表就用:select *
      ,最后一次出库数量=(select top 1 出库数量 from table_out where 货物名=a.货物名 order by 出库时间 desc)
      ,最后一次入库数量=(select top 1 入库数量 from table_in where 货物名=a.货物名 order by 入库时间 desc)
    into table_remain  --添加生成表的语句
    from(
    select 货物名=isnull(a.货物名,b.货物名)
      ,库存数量=sum(isnull(a.入库数量,0)-isnull(b.出库数量,0))
    from table_in a full join table_out on a.货物名=b.货物名
    group by isnull(a.货物名,b.货物名)
    ) a