[英]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:我有以下数据,并希望在 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如果我将变量设置为 n 值,则新列应从 1 开始,并包括变量
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:期望的输出:
This is the query, using modulus operator, the -1 is needed to make ROW_NUMBER
zero based:这是查询,使用模数运算符,需要 -1 来使ROW_NUMBER
从零开始:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.