Is it possible to write a window function that partitions every time when partition value changes?
For example:
create table test (id int, i int);
insert into test values (1, 1), (2, 0),(3, 0),(4, 1),(5, 1),(6, 1),(7, 0),(8, 0),(9, 1);
select
id,
i,
row_number() over (partition by i order by id asc) rn
from
test
order by
id asc;
will give me the following result:
id i rn
----------
1 1 1
2 0 1
3 0 2
4 1 2
5 1 3
6 1 4
7 0 3
8 0 4
9 1 5
However, I want to be able to restart the counter again when the value of i
is changed based on my sort order, regardless of whether it already appeared or not.
For example, the desired result would be this:
id i rn
----------
1 1 1
2 0 1
3 0 2
4 1 1
5 1 2
6 1 3
7 0 1
8 0 2
9 1 1
The same principle would apply for other window functions like cumulative sum for example.
I really don't want to loop just for this and I'm unable to find the right window function.
Thanks