如何在SQLite中计算不同利率的复利

时间:2018-05-26 17:49:28

标签: sql sqlite

我需要按产品计算复利,利息可能会按年变化。

下面的简化表格。 initial_value是第1年开始时的产品价值,final_value是包含相应年度末的利息的值。

product year    initial_value   interest    final_value
a         1       10000           0.03        10,300.00
a         2                       0.02        10,506.00
a         3                       0.01        10,611.06
b         1       15000           0.04        15,600.00
b         2                       0.06        16,536.00
b         3                       0.07        17,693.52

要重新创建表格:

CREATE TABLE temp (year INTEGER, product CHARACTER,
                   initial_value DECIMAL(10,2), interest DECIMAL(10,2));

INSERT INTO temp VALUES (1, 'a', 10000, 0.03);
INSERT INTO temp VALUES (2, 'a', 0, 0.02);
INSERT INTO temp VALUES (3, 'a', 0, 0.01);

INSERT INTO temp VALUES (1, 'b', 15000, 0.04);
INSERT INTO temp VALUES (2, 'b', 0, 0.06);
INSERT INTO temp VALUES (3, 'b', 0, 0.07);

以产品= a为例,第3年的数字应计算为10000 * (1+0.03) * (1+0.02) * (1+0.01)

产品的年数和数量可能会有所不同,因此我希望避免按年度转置数据,但遗憾的是,我们无法想到采用另一种方法来跨越行来获得所需的结果。

1 个答案:

答案 0 :(得分:3)

您可以使用RECURSIVE CTE

WITH RECURSIVE cte AS (
  SELECT year, product, initial_value, interest, initial_value*(1+ interest) AS s
  FROM temp
  WHERE initial_value <> 0
  UNION ALL
  SELECT t.year, t.product, t.initial_value, t.interest, s * (1+t.interest)
  FROM temp t
  JOIN cte c
    ON t.product = c.product
    AND t.year = c.year+1
)
SELECT *
FROM cte
ORDER BY product, year;

输出:

┌──────┬─────────┬───────────────┬──────────┬─────────────┐
│ year │ product │ initial_value │ interest │ final_value │
├──────┼─────────┼───────────────┼──────────┼─────────────┤
│    1 │ a       │         10000 │     0.03 │       10300 │
│    2 │ a       │             0 │     0.02 │       10506 │
│    3 │ a       │             0 │     0.01 │    10611.06 │
│    1 │ b       │         15000 │     0.04 │       15600 │
│    2 │ b       │             0 │     0.06 │       16536 │
│    3 │ b       │             0 │     0.07 │    17693.52 │
└──────┴─────────┴───────────────┴──────────┴─────────────┘

<强> DBFiddle Demo

修改

为了纯粹的乐趣,我用窗口函数重写了它:

SELECT *,
    FIRST_VALUE(initial_value) OVER(PARTITION BY product ORDER BY year) 
    * exp (sum (ln (1+interest)) OVER(PARTITION BY product ORDER BY year))
FROM temp;

<强> DBFiddle Demo2 - PostgreSQL

相关问题