A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Try this query:
;WITH CTE1 AS
(
SELECT *,SUM(vol)OVER(PARTITION BY cat1 ORDER BY [rank] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS SUM_Total
FROM #table1
),CTE2 AS
(
SELECT *,Vol_threshold-21 AS GAP1,LEAD(Vol_threshold)OVER(ORDER BY Rank)-21 AS GAP2
FROM #table2
)
SELECT C1.cat1,C1.vol,C2.Partition
FROM CTE1 C1 JOIN CTE2 C2 ON C1.SUM_Total >= GAP1 AND C1.SUM_Total < GAP2
Best regards,
Cosmog
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".