select a.日期,b.[商品名称表],a.入库数,a.出库数,
(select sum(入库数-出库数) from [库存明细表] where 商品ID=a.商品ID)
from [库存明细表] a inner join [商品名称表] b on a.商品ID=b.商品ID
(select sum(入库数-出库数) from [库存明细表] where 商品ID=a.商品ID)
from [库存明细表] a inner join [商品名称表] b on a.商品ID=b.商品ID
--测试环境
declare @商品名称表 table ( 商品ID varchar(10),商品名 varchar(20))
insert into @商品名称表 select '001','联想电脑'
union all select '002','DELL电脑'declare @库存明细表 table (商品ID varchar(10),日期 datetime,入库数 int ,出库数 int)
insert into @库存明细表 select '001','2005-1-1',10,0
union all select '001','2005-1-4',2,0
union all select '002','2005-1-4',1,0
union all select '001','2005-2-1',0,3
--查询语句
select 日期,
商品名称=(select 商品名 from @商品名称表 where 商品ID=a.商品ID),
入库数=a.入库数,
出库数=a.出库数,
实际库存=a.入库数-a.出库数
from @库存明细表 a--结果
日期 商品名称 入库数 出库数 实际库存
------------------------------------------------------ -------------------- ----------- ----------- -----------
2005-01-01 00:00:00.000 联想电脑 10 0 10
2005-01-04 00:00:00.000 联想电脑 2 0 2
2005-01-04 00:00:00.000 DELL电脑 1 0 1
2005-02-01 00:00:00.000 联想电脑 0 3 -3(所影响的行数为 4 行)
from 商品名称表 库存明细表
where 商品名称表.商品ID = 库存明细表.商品ID
group by 库存明细表.日期, 商品名称表.商品名称
declare @商品名称表 table ( 商品ID varchar(10),商品名 varchar(20))
insert into @商品名称表 select '001','联想电脑'
union all select '002','DELL电脑'declare @库存明细表 table (商品ID varchar(10),日期 datetime,入库数 int ,出库数 int)
insert into @库存明细表 select '001','2005-1-1',10,0
union all select '001','2005-1-4',2,0
union all select '002','2005-1-4',1,0
union all select '001','2005-2-1',0,3select 日期=convert(varchar(10),日期,120),
商品名称=(select 商品名 from @商品名称表 where 商品ID=a.商品ID),
入库数=a.入库数,
出库数=a.出库数,
实际库存=a.入库数-a.出库数
from @库存明细表 a--结果
日期 商品名称 入库数 出库数 实际库存
---------- -------------------- ----------- ----------- -----------
2005-01-01 联想电脑 10 0 10
2005-01-04 联想电脑 2 0 2
2005-01-04 DELL电脑 1 0 1
2005-02-01 联想电脑 0 3 -3(所影响的行数为 4 行)