我有一个查询返回库存详细信息,如下面SQL Server 2008中所示
在特定日期,项目A00001和A00002的库存余额分别为40,120。所以我想分配如下所示的值(按ItemCode,DateofReceipt desc排序)
任何人都可以帮助我如何更新第一个查询结果(我可以将这些值存储到临时表中,如果需要的话)以获得第二个表中的库存余额而不使用游标吗?
提前致谢!
答案 0 :(得分:0)
尝试
declare @tb table (itemCode varchar(10),DateofReceipt date,invno varchar(10), inqty int)
insert into @tb (itemcode,dateofReceipt,invno,inqty) values
('A00001','20150401','Inv01',100),
('A00001','20150410','Inv03',50),
('A00002','20150405','Inv02',100),
('A00002','20150415','Inv04',50)
declare @stock table(item varchar(10),qty int)
insert into @stock (item,qty) values
('A00001',50),('A00002',120)
;with cte as (select *,case when row_number() over(partition by itemCode order by DateofReceipt desc )=1 then qty else 0 end as stk,
row_number() over(order by itemcode, DateofReceipt desc) as rno
from @tb t inner join @stock s on t.itemCode=s.item),
ct1 (stock,bls,rno) as (select case when stk<=inqty then stk else inqty end as stock,case when stk<=inqty then 0 else stk-inqty end as bls,rno from cte where rno=1
union all select case when stk+bls<=inqty then stk+bls else inqty end as stock,case when stk+bls<=inqty then 0 else stk+bls-inqty end as bls,cte.rno from ct1 inner join cte on ct1.rno+1=cte.rno)
select itemcode,dateofReceipt,invno,inqty,stock from ct1 inner join cte on ct1.rno =cte.rno