Добрый день
Что касается FIFO по количеству или сумме, то тут вроде все понятно
А вот как сделать и по количеству и по сумме одновременно:
Получается так:
![Картинка с другого сайта.]()
А хотелось бы так:
Что касается FIFO по количеству или сумме, то тут вроде все понятно
А вот как сделать и по количеству и по сумме одновременно:
set nocount on -- Товары в Лицензиях if object_id('tempdb..#lic') is not null drop table #lic Create table #lic (licD date, licN int, itemN int, id int, kod_gr int, kod_prg int, qty int, amount money) insert into #lic select '2015-05-01', 1, 5, 23, 11, 1, 10, 1000 union select '2016-05-03', 3, 2, 23, 11, 1, 50, 5000 -- Товары в Отгрузке if object_id('tempdb..#otgr') is not null drop table #otgr create table #otgr (licN int, itemN int, id int, kod_gr int, kod_pgr int, qty int, price money, amount as qty*price) insert into #otgr(licN, itemN, id, kod_gr, kod_pgr, qty, price) select null, null, 23, 11, 1, 15, 150 union select null, null, 23, 11, 1, 25, 200 --select * from #lic --select * from #otgr if object_id('tempdb..#tl1') is not null drop table #tl1 select a.licD, a.LicN, a.ItemN, a.id, max(a.qty) qty, sum(b.qty)-max(a.qty) tot_qty, max(a.amount) as amount, sum(b.amount)-max(a.amount) as tot_amount into #tl1 from #lic a left outer join #lic b on b.licD < a.licD or (b.licD=a.licD and b.id<=a.id) group by a.licD, a.LicN, a.ItemN, a.id order by a.licD, a.id --select * from #tl1 if object_id('tempdb..#to1') is not null drop table #to1 select a.id, a.price, max(a.qty) qty, sum(b.qty)-max(a.qty) tot_qty, max(a.amount) as amount, sum(b.amount)-max(a.amount) as tot_amount into #to1 from #otgr a left outer join #otgr b on b.id<=a.id and b.price<=a.price group by a.id, a.price order by a.id --select * from #to1 select * from (select a.licN, a.itemN, b.id, case when a.tot_qty > b.tot_qty then case when (b.qty - (a.tot_qty - b.tot_qty)) > a.qty then a.qty when (b.qty - (a.tot_qty - b.tot_qty)) <= a.qty then b.qty - (a.tot_qty - b.tot_qty) end when a.tot_qty < b.tot_qty then case when (b.tot_qty + b.qty) - a.tot_qty >= a.qty then a.qty - (b.tot_qty - a.tot_qty) when (b.tot_qty + b.qty) - a.tot_qty < a.qty then b.qty end else case when a.qty > b.qty then b.qty else a.qty end end as cons_qty , case when a.tot_amount > b.tot_amount then case when (b.amount - (a.tot_amount - b.tot_amount)) > a.amount then a.amount when (b.amount - (a.tot_amount - b.tot_amount)) <= a.amount then b.amount - (a.tot_amount - b.tot_amount) end when a.tot_amount < b.tot_amount then case when (b.tot_amount + b.amount) - a.tot_amount >= a.amount then a.amount - (b.tot_amount - a.tot_amount) when (b.tot_amount + b.amount) - a.tot_amount < a.amount then b.amount end else case when a.amount > b.amount then b.amount else a.amount end end as cons_amount from #tl1 a cross join #to1 b ) as c where cons_qty>0 and cons_amount > 0 order by c.licN, c.itemN, c.id
Получается так:
А хотелось бы так: