基于数据组合的SQL Server行分区

时间:2016-11-02 11:15:48

标签: sql sql-server sql-server-2008

我的数据如下:

Create table #PP
(
MM int,
PP Int,
DT date
)

insert into #PP values(1,1,'2016-01-01')
insert into #PP values(1,1,'2016-02-01')
insert into #PP values(1,1,'2016-03-01') 
insert into #PP values(1,1,'2016-04-01') 
insert into #PP values(1,2,'2016-05-01') 
insert into #PP values(1,2,'2016-06-01') 
insert into #PP values(1,2,'2016-07-01') 
insert into #PP values(1,2,'2016-08-01') 
insert into #PP values(1,1,'2016-09-01') 
insert into #PP values(1,1,'2016-10-01') 
insert into #PP values(1,1,'2016-11-01') 
insert into #PP values(1,1,'2016-12-01') 

 select * from #PP 

My Data and What I am looking for

MM  PP  DT  Sr NO
1   1   01/01/2016  1
1   1   01/02/2016  2    
1   1   01/03/2016  3
1   1   01/04/2016  4
1   2   01/05/2016  1
1   2   01/06/2016  2
1   2   01/07/2016  3
1   2   01/08/2016  4
1   1   01/09/2016  1
1   1   01/10/2016  2
1   1   01/11/2016  3
1   1   01/12/2016  4

我已经编写了查询,但它无法正常工作

 SELECT MM, PP, DT
 , ROW_NUMBER() OVER(
                    PARTITION BY MM, PP
                    ORDER BY MM, PP
                    )  SRNO
 FROM #PP ORDER BY 1,2,3

我的查询结果如下,这是错误的 This is my Query Result

2 个答案:

答案 0 :(得分:1)

这个问题非常微妙。请务必注意,MMPP列中会重复这些值,但行号应重新开始。这很容易修复,使用行号的差异:

select mm, pp, dt,
       row_number() over (partition by mm, pp, seqnum - seqnum_mp order by dt) as srno
from (select p.*,
             row_number() over (partition by mm, pp order by dt) as seqnum_mp,
             row_number() over (order by dt) as seqnum
      from #pp p
     ) p;

Here是一个SQL小提琴,表明它有效。

答案 1 :(得分:0)

我写过,这对我有用

select mm, pp, dt,
      row_number() over (partition by mm, pp, seqnum - seqnum_mp order by dt) as srno
from (select p.*,
         row_number() over (partition by mm, pp order by dt) as seqnum_mp,
         row_number() over (order by mm,dt) as seqnum
  from #pp p
 ) p;