[英]Generated number sequence
Can anyone help me to generate number's sequence that repeat every n number n times. 谁能帮助我生成每n个数字重复n次的数字序列。 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.
看起来像这样的1、2、2、3、3、3、4、4、4、4 ...不需要使用临时表和循环就可以得到结果。
For example I can get simple sequence from 1 to 1000 using this code 例如,我可以使用此代码获得从1到1000的简单序列
;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): 对于直到2048的序列,您可以使用以下代码(不过,您可以轻松地对其进行修改以获取更多数字):
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 ║
╚════════╝
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.