sql - 对同一列的上一行进行递归操作(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 语言?谢谢你的帮助
解决方案
推荐阅读
- sas - SAS ODS 标记集 excelxp 网格线选项
- java - 仅使用 Google Guava 的缓存系统的优雅实现,它允许以与非空值不同的到期时间缓存空值?
- mysql - 值不保存到 mysql 数据库中
- typescript - 调用在打字稿中引用私有函数的公共函数时出现问题
- c - 如何使用 Paho 异步发布示例(MQTT C 客户端库)
- javascript - 在 Object ReactJS 中指定 id
- javascript - 正则表达式,JS:将文本匹配到特定单词之后的行尾,而不包括匹配中的单词
- matlab - 如何在 Parform matlab 中使用计数器
- arrays - 无法在 SerialPort 传输的接收端读取二进制数据作为字符串
- kotlin - 使 TornadoFX 窗口始终位于顶部