select t.*,
(first_value(calculation) over (partition by id order by <ordering col>) -
sum(transaction) over (partition by id order by <ordering col>)
) as calculation
from t
WITH
-- your input enhanced by row_num and expected result ...
input(id,row_num,transaction,calculation,expected) AS (
SELECT 123,1, 3.75,1.45,1.45
UNION ALL SELECT 123,2, 4.55,NULL,3.10
UNION ALL SELECT 123,3, 4.13,NULL,1.03
UNION ALL SELECT 456,1,12.3 ,3.22,3.22
UNION ALL SELECT 456,2, 2.22,NULL,-1
)
--输入结束。。。 --接下来是填充缺失值的第一次迭代 --注意named window子句- WINDOW w AS (....) ``` , fillonce AS ( SELECT id , row_num , transaction , calculation AS calc_org , FIRST_VALUE(calculation) OVER(w) - SUM(transaction) OVER(w) AS calculation , expected FROM input WINDOW w AS (PARTITION BY id ORDER BY row_num) )
SELECT id , row_num , transaction , calculation AS calc_org , IFNULL(calculation,transaction - LAG(calculation) OVER(w)) AS calculation , expected FROM fillonce WINDOW w AS (PARTITION BY id ORDER BY row_num) ;
2条答案
按热度按时间j9per5c41#
结果取决于数据的顺序。但是,sql表表示无序集。如果我假设您有一列指定了顺序,那么您需要这样的内容:
yx2lnoni2#
毕竟,我需要编辑这个。我尝试了@gordon linoff的方法,但没有成功,我在本文中提供了示例数据。
我会用
LAG()
olap函数。我还使用vertica的named window子句来提高可读性(WINDOW w AS ()
) .除此之外:您的excel工作表以迭代方式进行计算。你的
C4
计算出B4 - C3
,而C3
反过来,如你所示,计算为B3 - C2
. 所以我所能做的就是嵌套两个非常相似的查询:在您输入的第一个查询中
fillonce
,我设法计算出你的C3
,作为IFNULL(calculation,transaction-LAG(calculation) OVER(w))
(使用命名窗口)w
),意思是:如果calculation
不为空,请使用calculation
,否则减去calculation
上一行(LAG()
)从transaction
在这一排。最外面的查询从
fillonce
,并执行相同的操作。我补充道calc_org
作为原计算数,供参考。您的意见:
--输入结束。。。
--接下来是填充缺失值的第一次迭代
--注意named window子句-
WINDOW w AS (....)
```,
fillonce AS (
SELECT
id
, row_num
, transaction
, calculation AS calc_org
,
FIRST_VALUE(calculation) OVER(w)
- SUM(transaction) OVER(w)
AS calculation
, expected
FROM input
WINDOW w AS (PARTITION BY id ORDER BY row_num)
)
id | row_num | transaction | calc_org | calculation | expected
----+---------+-------------+----------+-------------+----------
123 | 1 | 3.75 | 1.45 | 1.45 | 1.45
123 | 2 | 4.55 | NULL | 3.10 | 3.10
123 | 3 | 4.13 | NULL | NULL | 1.03
456 | 1 | 12.30 | 3.22 | 3.22 | 3.22
456 | 2 | 2.22 | NULL | -1.00 | -1.00
SELECT
id
, row_num
, transaction
, calculation AS calc_org
, IFNULL(calculation,transaction - LAG(calculation) OVER(w)) AS calculation
, expected
FROM fillonce
WINDOW w AS (PARTITION BY id ORDER BY row_num)
;
id | row_num | transaction | calc_org | calculation | expected
-----+---------+-------------+----------+-------------+---------
123 | 1 | 3.75 | 1.45 | 1.45 | 1.45
123 | 2 | 4.55 | 3.10 | 3.10 | 3.10
123 | 3 | 4.13 | NULL | 1.03 | 1.03
456 | 1 | 12.30 | 3.22 | 3.22 | 3.22
456 | 2 | 2.22 | -1.00 | -1.00 | -1.00