T-SQL Row Number Restart after N

2020-06-28 09:50发布

问题:

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
148 6
149 7
150 8
151 9

INTO

ID  RowNumber
-------------
100 1
101 2
102 3
125 4
126 1
148 2
149 3
150 4
151 1

Note that there is no way to partition based on the ID, that is actually random.

I have tried to use a recursive CTE and got very close.

This:

DECLARE @MyTable TABLE (ID INT, RowNumber INT)

INSERT INTO @MyTable (ID,RowNumber)
    SELECT 100,1 UNION ALL
    SELECT 101,2 UNION ALL
    SELECT 102,3 UNION ALL
    SELECT 125,4 UNION ALL
    SELECT 126,5 UNION ALL
    SELECT 148,6 UNION ALL
    SELECT 149,7 UNION ALL
    SELECT 150,8 UNION ALL
    SELECT 151,9;

WITH CTE AS 
(
    SELECT  ID,
            RowNumber ,
            1 AS Steps
    FROM @MyTable   
    WHERE ID = 100

    UNION ALL
    SELECT M.ID ,
           M.RowNumber +1,
           CASE WHEN C.Steps = 4 THEN 0 ELSE C.Steps END +1 AS steps
    FROM @MyTable M
        INNER JOIN CTE C ON C.RowNumber = M.RowNumber

)
SELECT * 
FROM CTE

Returns:

ID  RowNumber
-------------
100 1   1
100 2   2
101 3   3
102 4   4
125 5   1
126 6   2
148 7   3
149 8   4
150 9   1
151 10  2

Which is very close apart from the first ID.

Any help would be great.

Thanks,

Will

回答1:

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;