Check a query:
;
with Q1 as
(
select *, row_number() over (partition by basin order by NumberInBasin) as n
from MyTable
),
Q2 as
(
select basin, prebasin, NumberInBasin, [Value], CumulativeBasin, NumberInBasinNew=NumberInBasin, n
from Q1
where n = 1
union all
select Q1.basin, Q1.prebasin, Q1.NumberInBasin, Q1.[Value], Q1.CumulativeBasin,
NumberInBasinNew =
CASE WHEN Q2.[Value] >= 1
OR
(
Q2.[Value] > 0
AND
(
Q2.[Value] >= 1
OR CEILING(Q2.CumulativeBasin) = Q2.CumulativeBasin
OR CEILING(Q1.CumulativeBasin) != CEILING(Q2.CumulativeBasin)
)
) THEN
Q2.NumberInBasinNew + 1
ELSE
Q2.NumberInBasinNew
END,
Q1.n
from Q2
inner join Q1 on Q1.basin=Q2.basin and Q1.n = Q2.n+1
)
select basin, prebasin, NumberInBasin, [Value], CumulativeBasin, NumberInBasinNew
from Q2
order by basin, NumberInBasin
option (maxrecursion 0)
If it does not work, show the mistake and the expected results.
It can be converted to UPDATE if needed.