• This query might help you

    Create Table WHS_Details (ItemCode VarChar(20),

    Quantity numeric(19, 6),

    Price numeric(19, 6),

    DocType VarChar(10),

    DocNum VarChar(12),

    DocDate Date ,

    TransID Int)

    Insert into WHS_Details values ('IT001',10,100,'PURCHASE',210000033,'2013-09-11',85)

    Insert into WHS_Details values ('IT002',10,1000,'PURCHASE',210000033,'2013-09-11',85)

    Insert into WHS_Details values ('IT001',6,200,'SALES',110000019,'2013-09-12',86)

    Insert into WHS_Details values ('IT001',5,200,'PURCHASE',210000034,'2013-09-13',87)

    Insert into WHS_Details values ('IT001',5,200,'SALES',110000019,'2013-09-14',88)

    select ItemCode, Price, DocDate, SUM(Quantity) as Quantity into #availQty from WHS_Details

    where DocType ='PURCHASE'

    group by ItemCode, Price, DocDate

    order by DocDate

    alter table #availQty ADD id int identity(1,1)

    declare @ItemCode VarChar(20),@Quantity numeric(19, 6), @id int, @availQty numeric(19, 6)

    declare soldqty cursor for select ItemCode,Quantity from WHS_Details where DocType='SALES'

    open soldqty

    fetch soldQty into @ItemCode, @Quantity

    while @@FETCH_STATUS = 0

    begin

    select top 1 @id=id, @availQty = Quantity from #availQty where ItemCode = @ItemCode

    order by DocDate

    if (@availQty < @Quantity)

    begin

    delete from #availQty where id=@id

    set @Quantity = @Quantity - @availQty

    end

    select top 1 @id=id, @availQty = Quantity from #availQty where ItemCode = @ItemCode

    order by DocDate

    update #availQty set Quantity = Quantity - @Quantity where id=@id

    fetch soldQty into @ItemCode, @Quantity

    end

    close soldqty

    deallocate soldqty

    select * from #availQty

    drop table #availQty

    drop table WHS_Details