如何在sql中生成Fibonacci系列!
我需要生成Fibonacci系列0 1 1 2 3 5 8 13 21 ... N
我使用C代码轻松地完成了这项工作,我需要使用Sql执行此操作!
答案 0 :(得分:14)
尝试此简单查询:
1)逐行结果(单列,多行)
WITH Fibonacci (PrevN, N) AS
(
SELECT 0, 1
UNION ALL
SELECT N, PrevN + N
FROM Fibonacci
WHERE N < 1000000000
)
SELECT PrevN as Fibo
FROM Fibonacci
OPTION (MAXRECURSION 0);
输出1:
2)仅针对一行中的结果(逗号拼写,单个单元格中)
WITH Fibonacci (PrevN, N) AS
(
SELECT 0, 1
UNION ALL
SELECT N, PrevN + N
FROM Fibonacci
WHERE N < 1000000000
)
SELECT Substring(
(SELECT cast(', ' as varchar(max)) + cast(PrevN as varchar(max)
);
FROM Fibonacci
FOR XML PATH('')),3,10000000) AS list
输出2:
答案 1 :(得分:4)
试试这个!
declare @a int
declare @b int
declare @c int
Declare @i int
set @a=0
set @b=1
set @i=0
set @c=0
Print 'Fibonacci Series'
print @a
print @b
while @i<10
Begin
set @c=@a+@b
print @c
set @i=@i+1
set @a=@b
set @b=@c
end
Fibonacci Series
0 1 1 2 3 五 8 13 21 34 55 89
答案 2 :(得分:3)
请尝试:
SELECT 0 AS fib_number UNION ALL
SELECT
FLOOR(POWER(( 1 + SQRT(5) ) / 2.0, number) / SQRT(5) + 0.5)
FROM master..spt_values
WHERE TYPE = 'p' AND number BETWEEN 1 AND 70
答案 3 :(得分:3)
试试这个: -
Declare @Fib int = 5
;with cte as
(
Select 0 as Previous,1 as Next ,0 as Level
union all
Select Next,Next + Previous,Level +1 from cte
where Level +1 <@Fib
)
Select Previous as FibonacciSeries from cte
答案 4 :(得分:0)
这是用于生成系列中的前10个数字。
DECLARE @NoOne INT, @NoTwo INT
DECLARE @FibonacciTable TABLE (Number INT NOT NULL)
--Insert first two numbers 0 and 1
INSERT @FibonacciTable (Number) SELECT 0 UNION ALL SELECT 1
SELECT @NoOne = 0, @NoTwo = 1
WHILE (SELECT COUNT(*) FROM @FibonacciTable) < 10
BEGIN
INSERT @FibonacciTable (Number) VALUES(@NoOne + @NoTwo)
SELECT @NoTwo = @NoOne + @NoTwo, @NoOne = @NoTwo - @NoOne
END
SELECT * FROM @FibonacciTable
GO
答案 5 :(得分:0)
CREATE TABLE #Fibonacci (value BIGINT)
GO
INSERT INTO #Fibonacci(value) SELECT 0
INSERT INTO #Fibonacci(value) SELECT 1
SELECT * FROM #Fibonacci
GO
INSERT INTO #Fibonacci(value)
SELECT SUM(value) FROM ( SELECT TOP 2 * FROM #Fibonacci ORDER BY value DESC ) AS value
GO 10 -- Loop insert 10 value...
SELECT * FROM #Fibonacci
DROP TABLE #Fibonacci
<强> Result Code 强>