I need to create a column that will start the count from 1 every time it finds a different value.
Here is an example of my table:
if object_id('tempdb.dbo.#myTable') is not null drop table #myTable
create table #myTable (dates int, flag char)
insert into #myTable values('20181031','V')
insert into #myTable values('20181130','V')
insert into #myTable values('20181231','V')
insert into #myTable values('20190131','F')
insert into #myTable values('20190228','F')
insert into #myTable values('20190331','F')
insert into #myTable values('20190430','F')
insert into #myTable values('20190531','V')
insert into #myTable values('20190630','V')
insert into #myTable values('20190731','V')
select *
from #myTable
order by 1
dates flag
20181031 V
20181130 V
20181231 V
20190131 F
20190228 F
20190331 F
20190430 F
20190531 V
20190630 V
20190731 V
I need the output to look as follows:
dates flag cnt
20181031 V 1
20181130 V 2
20181231 V 3
20190131 F 1
20190228 F 2
20190331 F 3
20190430 F 4
20190531 V 1
20190630 V 2
20190731 V 3
I have tried using variations of row_number()
with sub-queries, but I could not get it to start counting again when it hits the second set of Vs.
I looked at these two solutions, but I could not extrapolate it for my purpose:
Counting rows until where clause condition is saatisfied
Transact-SQL - number rows until condition met
I'm using SQL Server 2012
Thank you