This is a gaps and islands style problem. Without any sample data or desired results...
Using two row_number()
to identify groups by reset flag, and another in the outer query to number the rows by ResetFlag
and the grp
created in the inner query.
Change the order of date, Account, Side, Symbol, Currency
to whichever order of those columns you want to number the rows by; keep them in the same order for each of the three row_number()
s.
/* ----- */
select
date
, Account
, Side
, Symbol
, Currency
, ResetFlag
, rn = case when ResetFlag = 0 then 0
else row_number() over (
partition by ResetFlag, grp
order by date, Account, Side, Symbol, Currency)
end
from (
select *
, grp = row_number() over (order by date, Account, Side, Symbol, Currency)
- row_number() over (
partition by ResetFlag
order by date, Account, Side, Symbol, Currency)
from t
) s
order by date, Account, Side, Symbol, Currency
rextester demo: http://rextester.com/VLCO32635
returns:
+------------+---------+------+--------+----------+-----------+----+
| date | Account | Side | Symbol | Currency | ResetFlag | rn |
+------------+---------+------+--------+----------+-----------+----+
| 2017-01-01 | 7 | 2 | 3 | 7,0000 | 1 | 1 |
| 2017-01-02 | 8 | 9 | 9 | 6,0000 | 1 | 2 |
| 2017-01-03 | 4 | 1 | 5 | 6,0000 | 1 | 3 |
| 2017-01-04 | 5 | 4 | 8 | 5,0000 | 0 | 0 |
| 2017-01-05 | 2 | 1 | 3 | 1,0000 | 1 | 1 |
| 2017-01-06 | 8 | 0 | 2 | 0,0000 | 0 | 0 |
| 2017-01-07 | 0 | 3 | 8 | 9,0000 | 1 | 1 |
| 2017-01-08 | 0 | 3 | 1 | 3,0000 | 1 | 2 |
+------------+---------+------+--------+----------+-----------+----+