我有一个包含事件的表(比如X,Y,Z是随机事件,A,B是我想要跟踪的事件)。如果我找到事件A,我想在当前行和后续行上输出1,如果我在当前行和后续行中找到BI输出-1,在找到它们中的任何一个(A或B)之前我输出0.我如何使用Hive(SQL)做到这一点?
event | output | ordercol
X 0 1
Y 0 2
Z 0 3
B -1 4
X -1 5
X -1 6
B -1 7
X -1 8
A 1 9
X 1 10
B -1 11
Z -1 12
我知道这可以使用连接完成,但我正在寻找更优雅的解决方案(可能使用Window Functions - 我尝试过dense_rank()和row_count()但没有成功)
答案 0 :(得分:2)
根据此documentation,您可以使用first_value()
和其他一些逻辑:
select event,
(case first_value(case when event in ('A', 'B') then event end, true) over
(order by ordercol desc)
when 'A' then -1
when 'B' then 1
else 0
end)
from e;
此功能在标准和其他数据库中称为IGNORE NULLS
。