Reputation: 897
Can anyone help me to generate number's sequence that repeat every n number n times. It would look like like this 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 ... It will be nice to get result without using temporary tables and loops.
For example I can get simple sequence from 1 to 1000 using this code
;WITH n(n) AS
(
SELECT 1
UNION ALL
SELECT n+1 FROM n WHERE n < 1000
)
SELECT n FROM n ORDER BY n
OPTION (MAXRECURSION 1000);
But how to reorganise code to get sequence described above?
Upvotes: 0
Views: 116
Reputation: 70638
For a sequence till 2048, you can use this code (you can easily modify it to get more numbers though):
DECLARE @N INT;
SET @N = 5;
WITH Numbers AS
(
SELECT number + 1 number
FROM master.dbo.spt_values
WHERE type = 'P'
)
SELECT A.number
FROM Numbers A
CROSS JOIN Numbers B
WHERE A.number >= B.number
AND A.number <= @N
ORDER BY A.number;
Here is a demo for you to try.
And the results are:
╔════════╗
║ number ║
╠════════╣
║ 1 ║
║ 2 ║
║ 2 ║
║ 3 ║
║ 3 ║
║ 3 ║
║ 4 ║
║ 4 ║
║ 4 ║
║ 4 ║
║ 5 ║
║ 5 ║
║ 5 ║
║ 5 ║
║ 5 ║
╚════════╝
Upvotes: 4