在 Hive 中加入日期范围内的表

Join Tables on Date Range in Hive

我需要在 employee_id 加入 tableA 到 tableB 和 table 的 cal_date A 需要在日期开始和日期之间end from table B. 我在运行下方查询,收到如下错误信息,请您帮我更正查询。谢谢你的帮助!

JOIN中遇到左右别名'date_start'.

select a.*, b.skill_group 
from tableA a 
  left join tableB b 
    on a.employee_id= b.employee_id 
    and a.cal_date >= b.date_start 
    and a.cal_date <= b.date_end

RTFM - 引用 LanguageManual Joins

Hive does not support join conditions that are not equality conditions as it is very difficult to express such conditions as a map/reduce job.

您可能会尝试将 BETWEEN 过滤器移动到 WHERE 子句,导致糟糕的部分笛卡尔连接,然后是 post 处理清理。呸。根据您 "skill group" table 的实际基数,它可能工作得很快 - 或者需要一整天。

如果您的情况允许,请分两次查询。

首先是full join,可以有范围;然后使用外连接,匹配所有列,但包含一个 where 子句,其中一个字段为空。

例如:

create table tableC as
select a.*, b.skill_group 
    from tableA a 
    ,    tableB b 
    where a.employee_id= b.employee_id 
      and a.cal_date >= b.date_start 
      and a.cal_date <= b.date_end;

with c as (select * from TableC)
insert into tableC
select a.*, cast(null as string) as skill_group
from tableA a 
  left join c
    on (a.employee_id= c.employee_id 
    and a.cal_date  = c.cal_date)
where c.employee_id is null ;

MarkWusinich 有一个很好的解决方案,但有一个主要问题。如果 table a 在 table 日期范围内有两次员工 ID,c 也会有 employee_ID 两次(如果 b 是唯一的,如果不是更多的话)在加入后创建 4 条记录。因此,如果 A 在 employee_ID 上不是唯一的,则需要分组依据。更正如下:

with C as
(select a.employee_id, b.skill_group 
    from tableA a 
    ,    tableB b 
    where a.employee_id= b.employee_id 
      and a.cal_date >= b.date_start 
      and a.cal_date <= b.date_end
group by a.employee_id, b.skill_group
) C
select a.*, c.skill_group
from tableA a 
left join c
  on a.employee_id = c.employee_id 
    and a.cal_date  = c.cal_date;

请注意:如果 B 在 (employee_id、skill_group) 上故意不区分,那么我上面的查询也必须修改以适当地反映这一点。