Я думаю, что это сделает это.
declare @Table1 table (
Cat int,
TOP_Limit int
)
declare @Table2 table (
Part int,
Cat int,
Quantity int
)
insert into @Table1
(Cat, TOP_Limit)
select 1,1 union all
select 2,2 union all
select 3,10
insert into @Table2
(Part, Cat, Quantity)
select 2,1,20 union all
select 3,2,100 union all
select 4,2,100 union all
select 5,2,50 union all
select 6,3,5
;with cteRowNums as (
select t2.Part, t2.Cat, t2.Quantity,
ROW_NUMBER() over(partition by t2.Cat order by t2.Quantity desc, t2.Part) as rownum
from @Table2 t2
inner join @Table1 t1
on t2.Cat = t1.Cat
)
select c.Part, c.Cat, c.Quantity
from cteRowNums c
inner join @Table1 t1
on c.Cat = t1.Cat
and c.rownum <= t1.TOP_Limit