create table #t_Jenas (Id int, Name char)
insert into #t_Jenas values
(1, 'A'),
(2, 'A'),
(3, 'B'),
(4, 'B'),
(5, 'B'),
(6, 'B'),
(7, 'C'),
(8, 'B'),
(9, 'B')
对于行号分区,如果重复的行,数字将继续,使得减号列不升序。知道如何使分区号从 1 开始,尽管重复行作为上面的数据?
select name,row_number() over (order by id) as cont ,row_number() over (partition by name order by id) as newcount,( row_number() over (order by id)-row_number() over (partition by name order by id)) as rowminusnewcount --, count(*) as cnt
from #t_Jenas
实际的:
name cont newcount rowminusnewcount
A 1 1 0
A 2 2 0
B 3 1 2
B 4 2 2
B 5 3 2
B 6 4 2
C 7 1 6
B 8 5 3
B 9 6 3
预期的:
name cont newcount rowminusnewcount
A 1 1 0
A 2 2 0
B 3 1 2
B 4 2 2
B 5 3 2
B 6 4 2
C 7 1 6
B 8 1 7
B 9 2 7