I am trying to apply ROW_NUMBER()
to increment a counter based on particular conditions.
My data looks like this, with the target counter being the Prep
column
id DSR PrepIndicator Prep
--------------------------------------
1662835 -1 1 1
1662835 14 2 2
1662835 14 2 3
1662835 20 2 4
1667321 -1 1 1
1667321 30 2 2
1667321 14 2 3
1680648 -1 1 1
1680648 14 2 2
1680648 60 1 1
1680648 14 2 2
1680648 14 2 3
1683870 -1 1 1
1683870 12 2 2
1683870 10 2 3
1683870 60 1 1
1683870 7 2 2
Ignoring the PrepIndicator
column for the moment, the business logic I am trying to implement is as follows:
- For each of the Id's, starting from 1, increment the
Prep
counter if the DSR is less than 42. - If it is 42 or greater, reset the Prep counter to 1.
The PrepIndicator
, in effect, creates a flag to implement this, in that if PrepIndicator = 1
then Prep = 1
. If PrepIndicator = 2
, then increment Prep
.
I'd prefer to achieve this without the PrepIndicator
column if possible.
How would I achieve this conditional increment with ROW_NUMBER()
?
I've tried
ROW_NUMBER() OVER (PARTITION BY id, PrepIndicator ORDER BY id)
but it doesn't seem to work when the DSR
is >= 42
.
Any suggestions or help would be great. Thanks!