简体   繁体   中英

Count Number of Consecutive Occurrence of values in Table with new partition count although repeated rows

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')

for row number partition by, if repeated rows, the number will continue that makes the minus column is not ascending. any idea how to make the partition number starts from 1 although repeat rows as data above?

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

Actual:

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

Expected:

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

I figured out the meaning of the last column:

select name, id,
       row_number() over (partition by grp, name order by id) as new_count,
       count(*) over (order by min_grp_id) - count(*) over (partition by grp, name)
from (select t.*, min(id) over (partition by grp, name) as min_grp_id
      from (select t.*,
                   (row_number() over (order by id) - row_number() over (partition by name order by id)
                   ) as grp
            from t_Jenas t
           ) t
     ) t
order by id;

Here is a db<>fiddle.

My guess is cont , newcount and rowminusnewcount all are row_numbers. I modified id to show the idea.

create table #t_Jenas (Id int, Name char);

insert into #t_Jenas values
(10, 'A'),
(20, 'A'),
(30, 'B'),
(40, 'B'),
(50, 'B'),
(60, 'B'),
(70, 'C'),
(80, 'B'),
(90, 'B');

select name,  cont,
       row_number() over (partition by grp, name order by id) as new_count,
       cont - row_number() over (partition by grp, name order by id) rowminusnewcount 
from (
 select t.*, row_number() over (order by id) as cont
      , row_number() over (order by id) - row_number() over (partition by name order by id) as grp
       from #t_Jenas t
     ) t
order by id

Result

name    cont    new_count   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM