JonWay
JonWay

Reputation: 1735

Dynamically get row number interval based on specified number in SQL Server

I have the data below and want to sub group the data by a given number in SQL Server:

CREATE TABLE #TBL (ID INT)

INSERT INTO #TBL 
VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), 
       (10), (11), (12), (13), (14), (15), (16), (17), (18), (19), (20);

If I set the variable to n values the new column should start from 1 upto and including the variable

I tried this but I cannot get it to work

DECLARE @N INT = 5

SELECT
    ID
    ,ROW_NUMBER() OVER(ORDER BY ID) AS RN  
    ,CASE WHEN ROW_NUMBER() OVER(ORDER BY ID) > @N THEN ROW_NUMBER() OVER(ORDER BY ID)-@N 
          ELSE ROW_NUMBER() OVER(ORDER BY ID) END AS New
FROM 
    #TBL

Current output

ID  RN  New
---------------
1   1   1
2   2   2
3   3   3
4   4   4
5   5   5
6   6   1
7   7   2
8   8   3
9   9   4
10  10  5
11  11  6
12  12  7
13  13  8
14  14  9
15  15  10
16  16  11
17  17  12
18  18  13
19  19  14
20  20  15

Desired output:

enter image description here

Upvotes: 3

Views: 1355

Answers (3)

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

DB FIDDLE

DECLARE @N INT=8

SELECT ID, ROW_NUMBER() OVER(ORDER BY ID) AS RN,
    CAST(ROW_NUMBER() OVER(ORDER BY ID) AS DECIMAL) % @N + 1 AS New
FROM #TBL

Upvotes: 1

Nicola Lepetit
Nicola Lepetit

Reputation: 795

This is the query, using modulus operator, the -1 is needed to make ROW_NUMBER zero based:

CREATE TABLE #TBL (ID INT);

INSERT INTO #TBL VALUES
(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),
(12),(13),(14),(15),(16),(17),(18),(19),(20);
DECLARE @N INT=5

SELECT
    ID,
    ROW_NUMBER() OVER (ORDER BY ID) RN,
    ((ROW_NUMBER() OVER (ORDER BY ID) -1) % @N) +1 NEW
FROM #TBL;

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521409

I think you want to use ROW_NUMBER with a partition of the ID minus one, divided by 5:

DECLARE @N INT = 5;

SELECT
    ID,
    ROW_NUMBER() OVER (ORDER BY ID) RN,
    ROW_NUMBER() OVER (PARTITION BY (ID-1) / @N ORDER BY ID) NEW
FROM #TBL;

screen capture of demo below

Demo

Upvotes: 3

Related Questions