尽管重复行,但具有新分区计数的表中值连续出现的次数

时间:2019-05-12 12:42:22

标签: sql sql-server row-number partition-by

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

2 个答案:

答案 0 :(得分: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;

Here是db <>小提琴。

答案 1 :(得分:0)

我的猜测是contnewcountrowminusnewcount都是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