Hive sql连接表找到最接近的行

时间:2016-05-23 13:34:36

标签: sql hive hiveql

我有以下表格:

Tbl1:

public static <T> List<T> concat(List<T> lst1, List<T> lst2){
    //lst1.stream().flatMap() - it maps each elements 
                                //of lst1 to stream and concatenates it for each                                          
                                //element    
}

Tbl2:

V1 | V2 | Time
x    A    1
x    B    4
y    C    5

我希望以一种获得以下结果的方式加入他们

V1 | Time 
x    2
x    4
y    1 

换句话说,我想加入V1上的表格并从Tbl2获取V2,其中Tbl1.Time&lt; Tbl2.Time和(Tbl2.Time - Tbl1.Time)获得最小值。有什么建议?

1 个答案:

答案 0 :(得分:0)

在其他数据库中,您将使用相关子查询。这不是一种选择。创建笛卡尔积然后聚合是另一种方法 - 它适用于较小的表。

另一种方法是交错两个表,使用累积函数,然后从第一个表中选择:

select v1, v2, time, t2time
from (select v1, v2, time,
             max(time) over (partition by v1
                             order by time, v2 as nulls first
                            ) as t2time
      from ((select v1, v2, time
             from table1
            ) union all
            (select v1, NULL, time
             from table2
            )
           ) t
     ) t
where v2 is not null;  -- Remove table2 records

我没有在Hive中使用这种方法。我发现它在Oracle,SQL Server和Postgres中非常有效。