I am not sure that I understand the logic exactly, but maybe this can help you in the right direction:
CREATE TABLE #table1 (cat1 varchar(20),
vol int,
rank int)
INSERT #table1(cat1, vol, rank)
VALUES('Cat1', 1, 1),
('Cat1', 4, 2),
('Cat1', 6, 3),
('Cat1', 16, 4)
CREATE TABLE #table2 (Rank int,
Vol_threshold int,
Partition int)
INSERT #table2(Rank, Vol_threshold, Partition)
VALUES(1, 21, 1),
(2, 27, 2),
(3, 34, 3)
; WITH runsum AS (
SELECT t1.cat1, (SELECT t2.Vol_threshold FROM #table2 t2 WHERE t2.Rank = 1) +
SUM(t1.vol) OVER(PARTITION BY t1.cat1
ORDER BY t1.rank
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS runsum
FROM #table1 t1
)
SELECT r.cat1, r.runsum, t2.Partition
FROM runsum r
OUTER APPLY (SELECT TOP(1) t2.Partition
FROM #table2 t2
WHERE t2.Vol_threshold <= r.runsum
ORDER BY t2.Partition DESC) t2
go
DROP TABLE #table1, #table2