简体   繁体   中英

Generated number sequence

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?

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 ║
╚════════╝

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM