T-SQL Row Number Restart after N

后端 未结 1 707
臣服心动
臣服心动 2021-01-03 15:54

How can I restart my Row_Number after a certain number of rows.

E.g.

How can I turn

ID  RowNumber
-------------
100 1
101 2
102 3
125 4
126 5         


        
相关标签:
1条回答
  • 2021-01-03 16:20

    Use the modulo operator:

    select id, rownumber, 1 + ((rownumber - 1) % 4)
    from table t;
    

    If rownumber is not a column, you can also use the row_number() function:

    select id, row_number() over (order by id),
           1 + ((row_number() over (order by id) - 1) % 4)
    from table t;
    
    0 讨论(0)
提交回复
热议问题