if object_id('[tb]') is not null drop table [tb]
create table [tb] (STORE varchar(6),BC varchar(5),BD varchar(10),GOODS varchar(5),QTY int,PRICE numeric(8,2),AM varchar(5),[ISIN] varchar(4))
insert into [tb]
select '原料仓','IN001','2009-07-30','A001','300','20','6000','1' union all
select '原料仓','IN002','2009-07-29','B001','400','2','800','1' union all
select '原料仓','IN101','2009-08-01','A001','30','20','600','1' union all
select '原料仓','IN103','2009-08-20','A001','50','22','1100','1' union all
select '原料仓','IN203','2009-08-25','A001','20','23','460','1' union all
select '原料仓','IN123','2009-08-26','B001','300','2','600','1' union all
select '原料仓','OU100','2009-08-26','A001','30','0','0','0' union all
select '原料仓','OU202','2009-08-27','B001','20','0','0','0' union all
select '原料仓','OU132','2009-08-29','A001','40','0','0','0' union all
select '原料仓','IN123','2009-09-01','A001','500','21','10500','1' union all
select '原料仓','IN125','2009-09-20','B001','500','2.2','1100','1' union all
select '半成仓','OU129','2009-09-25','B001','23','0','0','1' union all
select '原料仓','OU211','2009-09-08','A001','100','0','0','0' union all
select '原料仓','OU213','2009-09-27','B001','120','0','0','0' union all
select '原料仓','OU129','2009-09-25','B001','23','0','0','0'
go
create proc wsp
@fromdate datetime,
@todate datetime
as
select a.*,期初数量=b.qty,期初单价=b.price,期初金额=b.qty*b.price,收入数量,收入单价,收入金额=收入数量*收入单价,
发出数量,发出单价,发出金额=发出数量*发出单价
from
(select store,goods
from [tb] a where bd between @fromdate and @todate group by store,goods)a,
(select * from tb a where bd<@fromdate and (select count(distinct bd) from tb where bd<@fromdate and STORE=a.STORE and goods=a.goods and bd>=a.bd)=1)b,
(select store,goods,收入数量=sum(qty),收入单价=avg(price) from tb a where bd between @fromdate and @todate and isin=1 group by store,goods )c,
(select store,goods,发出数量=sum(qty),发出单价=avg(price) from tb a where bd between @fromdate and @todate and isin=0 group by store,goods )d
where a.store=b.store and a.store=c.store and a.store=d.store and a.goods = b.goods and a.goods = c.goods and a.goods = d.goods
go
--调用:
exec wsp '2009-08-01','2009-08-31'