首页 > 解决方案 > 对同一列的上一行进行递归操作(AWS Athena = Presto SQL)

问题描述

我正在尝试将公式从 Google Sheet 文件转换为 SQL。我陷入了递归公式(调用同一列上一行的结果)。

这是我正在使用的表

timestamp   var1
1602460890  1
1602460900  3
1602460910  4
1602460920  4
1602460930  1
1602460940  8
1602460950  2
1602460960  3
1602460970  4
1602460980  2

我希望得到以下结果,并添加“var2”列

timestamp   var1  var2
1602460890  1   
1602460900  3     1   # 1 = 1 + 3 * 0
1602460910  4     5   # 5 = 1 + 4 * 1 
1602460920  4     21  # 21 = 1 + 4 * 5 
1602460930  1     0   # Here the result is "0" because in the previous line, the result is greater than a threshold (the threshold is set at 10)
1602460940  8     1   # 1 = 1 + 8 * 0 
1602460950  2     3   # 3 = 1 + 2 * 1 
1602460960  3     10  # 10 = 1 + 3 * 3 
1602460970  4     41  # 41 = 1 + 4 * 10 
1602460980  2     0   # Here the result is "0" because in the previous line, the result is greater than a threshold (the threshold is set at 10)

“var2”等于1,我们将“var1”乘以“var2”的前一个结果。但如果它之前的结果大于 10(阈值设置为 10),那么结果将为零。

SQL 查询可能看起来像这样,但这个查询在逻辑上会返回以下错误:

“SYNTAX_ERROR:第 3:18 行:无法解析列 'var2'”

SELECT *,
   (CASE
       WHEN (lag(var2, 1) OVER (ORDER BY timestamp)) > 10  -- (the threshold is set at 10)
       THEN 0
       ELSE 1 + (var1 * (lag(var2, 1) OVER (ORDER BY timestamp))) END)
    AS var2
FROM my_table

有没有人有解决这个问题的想法,或者我必须更改 SQL 语言?谢谢你的帮助

标签: sqlamazon-web-servicesprestoamazon-athena

解决方案


推荐阅读