SQL Server 2008中的排序和重新设置

时间:2014-09-19 10:49:43

标签: sql sql-server-2008

我实际上是SQL Server 2008的新手,我正在尝试对表中的数字进行排序和重新设置。来源类似于:

Row   Refrec FLAG 
1     5      NULL  
2     4      X    
3     3      NULL 
4     2      NULL 
5     1      Y     
6     5      A    
7     4      B         
8     3      NULL  
9     2      NULL 
10    1      NULL 

结果如下:

Row   Refrec FLAG SEQUENCE
1     5      NULL  NULL 
2     4      X     0
3     3      NULL  1
4     2      NULL  2
5     1      Y     0 
6     5      A     0
7     4      B     0     
8     3      NULL  1 
9     2      NULL  2
10    1      NULL  3

谢谢!

1 个答案:

答案 0 :(得分:2)

看起来您想要枚举NULL值的序列值,将所有其他值设置为0。我不确定为什么第一个值是NULL,但很容易修复。

以下可能会做你想要的:

select t.*,
       (case when flag is not null then 0
             else row_number() over (partition by seqnum - row order by row)
        end) as Sequence
from (select t.*, row_number() over (partition by flag order by row) as seqnum
      from table t
     );

如果你真的关心第一个值:

select t.*,
       (case when row = 1 then NULL
             when flag is not null then 0
             else row_number() over (partition by seqnum - row order by row)
        end) as Sequence
from (select t.*, row_number() over (partition by flag order by row) as seqnum
      from table t
     );