我有一个包含以下列的表格:
ID, date, amount, amount2
amount2 列仅在第一行中有值。我需要使用该列前一行的值以及列 amount 来递归计算 amount2 列的每一行
amount2 的第二行应该是:第二行 amount + amount 的第一行值 - amount2 的第一行值 amount2 的第三行应该是:第三行金额 + 第二行 amount 的值 - 第二行 amount2 的值...
我尝试使用以下代码,但它不起作用:
SELECT
first_column,
CASE
WHEN second_column IS NULL THEN LAG(first_column, 1, first_column) OVER (ORDER BY row_id) - LAG(first_column, 1, first_column) OVER (ORDER BY row_id DESC)
ELSE second_column
END AS calculated_second_column
from table;
可重现的示例:
CREATE TABLE your_table_name (
id INT,
date DATE,
amount DECIMAL(10,2),
amount1 DECIMAL(10,2)
);
INSERT INTO your_table_name (id, date, amount, amount1)
VALUES
(234, '2020-01-01', 4, 10),
(234, '2020-01-02', 7, NULL),
(234, '2020-01-03', 10, NULL),
(234, '2020-01-04', 15, NULL),
(234, '2020-01-05', 6, NULL);
我希望在 amount1 栏中有; 10, 7+4-10=1, 10+7-1=16, 15+10-16=9, 6+15-9=12
您可以使用:
SELECT id, dt, amount, amount1
FROM (
SELECT t.*, ROW_NUMBER() OVER (PARTITION BY id ORDER BY dt) AS rn
FROM your_table_name t
)
MODEL
PARTITION BY (id)
DIMENSION BY (rn)
MEASURES (dt, amount, amount1)
RULES (
amount1[rn>1] = amount[cv(rn)] + amount[cv(rn)-1] - amount1[cv(rn) - 1]
);