gpt4 book ai didi

sql - Hive 访问上一行值

转载 作者:可可西里 更新时间:2023-11-01 15:12:32 25 4
gpt4 key购买 nike

我也有同样的问题 here

但是,问题出在 Hive 数据库上。当我在我的 table 上尝试解决方案时,看起来像

Id   Date             Column1    Column2
1 01/01/2011 5 5 => Same as Column1
2 02/01/2011 2 18 => (1 + (value of Column2 from the previous row)) * (1 + (Value of Column1 from the current row)) i.e. (1+5)*(1+2)
3 03/01/2011 3 76 => (1+18)*(1+3) = 19*4

我得到了错误

FAILED: SemanticException Recursive cte cteCalculation detected (cycle: ctecalculation -> cteCalculation).

在这种情况下可能的解决方法是什么

最佳答案

你必须为此编写一个 UDF。
您可以在下面看到一个非常(!!)简化的 UDF,以满足您的需求。
这个想法是将上一次执行的值存储在 UDF 内的一个变量中,每次返回 (stored_value+1)*(current_value+1) 然后将其存储到下一行。
您需要处理要获取的第一个值,因此有一个特殊情况。
此外,您必须将排序的数据传递给函数,因为它只是逐行执行并执行您需要的操作而不考虑任何顺序。

您必须添加您的 jar 并创建一个函数,我们将其命名为 cum_mul

SQL 将是:

select id,date,column1,cum_mul(column1) as column2
from
(select id,date,column1 from myTable order by id) a

UDF 的代码:

import org.apache.hadoop.hive.ql.exec.UDF;

public class cum_mul extends UDF {

private int prevValue;
private boolean first=true;

public int evaluate(int value) {
if (first) {
this.prevValue = value;
first = false;
return value;
}
else {
this.prevValue = (this.prevValue+1)*(value+1);
return this.prevValue;
}
}
}

关于sql - Hive 访问上一行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34101365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com