postgresql 具有表值的递归函数

92dk7w1h  于 2023-06-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(108)

我有一个表evenfib,看起来像这样:
| n| n |
| - -----| ------------ |
| 十个| 10 |
| 一百| 100 |
| 一千| 1000 |
我需要得到所有小于给定数字n的偶数斐波那契数的总和
我想出了如何获得一个具有静态限制的fiboacci序列,但我不明白如何使用它与表中的值。
我使用的是PostgreSQL 13.0,代码如下:

WITH RECURSIVE fibonacci(prev_n, n) AS (
  SELECT 0::bigint, 1::bigint
  UNION ALL
  SELECT n, prev_n + n AS fib FROM fibonacci WHERE n < 100
)

SELECT SUM(prev_n)::INT
FROM fibonacci
WHERE prev_n % 2 = 0

这段代码返回44(0.44e2,没有转换为INT),它工作得很好,因为斐波那契数列低于100是0 1 1 2 3 5 8 13 21 34 55 89,所以2 + 8 + 34 = 44。
但是我希望能够将第4行末尾的100更改为evenfib表中的值。

hmtdttj4

hmtdttj41#

你可以用

WITH RECURSIVE fibonacci(id, prev_n, n) AS (
  SELECT id, 0::bigint, 1::bigint
  FROM evenfib
  UNION ALL
  SELECT id, fib.n, fib.prev_n + fib.n
  FROM fibonacci fib
  JOIN evenfib USING (id)
  WHERE fib.n < evenfib.n
)

SELECT id, SUM(prev_n)::INT
FROM fibonacci
WHERE prev_n % 2 = 0
GROUP BY id;

online demo
或者,只需在evenfibs上使用子查询,而不是静态限制:

WITH RECURSIVE fibonacci(prev_n, n) AS (
  SELECT 0::bigint, 1::bigint
  UNION ALL
  SELECT n, prev_n + n
  FROM fibonacci
  WHERE n < (SELECT max(n) FROM evenfib)
)

SELECT id, SUM(prev_n)::INT
FROM fibonacci, evenfib
WHERE prev_n % 2 = 0
  AND prev_n < evenfib.n
GROUP BY id;

online demo

相关问题