declare @total decimal(9,3), @sl_no int
select @total = 25.000, @sl_no = 0 -- first case
--select @total = 30.000, @sl_no = 3 -- second case
;with tab (Product, sl_no, Wt_Kg) as (
select 'Prod-001', 1, 3.000 union all
select 'Prod-002', 2, 4.000 union all
select 'Prod-003', 3, 2.000 union all
select 'Prod-004', 4, 3.000 union all
select 'Prod-005', 5, 6.000 union all
select 'Prod-006', 6, 7.000 union all
select 'Prod-007', 7, 1.000 union all
select 'Prod-008', 8, 2.000 union all
select 'Prod-009', 9, 3.000 union all
select 'Prod-010', 10, 5.000 union all
select 'Prod-011', 11, 2.000 union all
select 'Prod-012', 12, 4.000
)
select t3.*
from tab t3
join (
select t1.product, t1.sl_no, sum(t2.Wt_Kg) as total
from tab t1
join tab t2 on t1.sl_no >= t2.sl_no
where t2.sl_no >= @sl_no
group by t1.product, t1.sl_no
) t on t.product = t3.product and t.sl_no = t3.sl_no
where t.total <= @total
Добавлено : группировка и объединение по sl_no
(на тот случай, если product
не является уникальным)
Результаты в первом случае:
Product sl_no Wt_Kg
Prod-001 1 3.000
Prod-002 2 4.000
Prod-003 3 2.000
Prod-004 4 3.000
Prod-005 5 6.000
Prod-006 6 7.000
второй случай:
Product sl_no Wt_Kg
Prod-003 3 2.000
Prod-004 4 3.000
Prod-005 5 6.000
Prod-006 6 7.000
Prod-007 7 1.000
Prod-008 8 2.000
Prod-009 9 3.000
Prod-010 10 5.000