0
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
4

2 回答 2

0

我的猜测是contnewcount而且rowminusnewcount都是 row_numbers。我修改id以展示这个想法。

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

结果

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
于 2019-05-12T13:11:47.423 回答
0

我弄清楚了最后一列的含义:

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;

是一个 db<>fiddle。

于 2019-05-12T12:48:23.907 回答