Hive QL 列中两个最接近的元素之间的差异

Hive QL Difference between two closest elements in a column

假设我有一个非常简单的 table 像这样:

ID: Integer
A    4
A    9
A    2
B    4 
B    7
B    3

而且我想要 groupBy(ID)。告诉我最小差异的适当查询是什么 - 就像这样

ID: MIN_DIF:
A    2
B    1

现在查询的简单性比效率更重要,但最基本和最高效的查询都会受到赞赏。

旁注:找到平均距离会很不错,但我首先需要最小值

您可以使用 lag()lead():

select id, min(int - prev_int)
from (select t.*, lag(int) over (partition by id order by int) as prev_int
      from t
     ) t
group by id
where prev_int is not null;

另一种方法避免了 window 函数,但性能可能更差:

select t.id, min(t2.integer - t.integer)
from t join
     t t2
     on t.id = t2.id 
where t2.integer > t.integer
group by t.id;