;WITH TT
AS
(SELECT WEEK,itemid,CASE WHEN RIGHT(CONVERT(VARCHAR,week),2) = '00' THEN qty ELSE - qty END AS qty
FROM tb1),
T1
AS(
SELECT TOP 100 A.week,a.itemid,a.qty,CASE WHEN SUM(b.qty) > 0 THEN 0 ELSE SUM(b.qty) END AS sqty,
CASE WHEN SUM(b.qty)<0 THEN 1 ELSE 0 END AS mark
FROM TT A
INNER JOIN TT B ON A.itemid = B.itemid AND A.[week] >= b.[week]
GROUP BY A.week,a.itemid,a.qty
ORDER BY a.itemid,a.week
),
T2
AS(
SELECT *,ROW_NUMBER() OVER(PARTITION BY itemid,mark ORDER BY week ) AS num
FROM T1)