WITH
cte1 AS ( SELECT CodeGoods,
Validate,
Mass,
SUM(Mass) OVER (PARTITION BY CodeGoods ORDER BY Validate) CumMass
FROM Rest ),
cte2 AS ( SELECT cte1.CodeGoods,
cte1.Validate,
cte1.Mass,
COALESCE(LAG(CumMass) OVER (PARTITION BY cte1.CodeGoods ORDER BY cte1.Validate), 0) LagMass
FROM cte1 )
SELECT cte2.CodeGoods,
cte2.Validate,
cte2.Mass
FROM cte2
JOIN Orders ON Orders.CodeGoods = cte2.CodeGoods
AND Orders.Mass >= cte2.LagMass