【问题标题】:Left Join in Hive is not returning expected resultsHive 中的左连接未返回预期结果
【发布时间】:2020-12-16 08:40:04
【问题描述】:

我有3张表,一张是只包含日期的datetable,另外2张的数据如下。

日期表:

表1:

表2:

我正在使用日期表进行左连接,如下所示:

select * from 
(select distinct t.d,
coalesce(tab1.name,tab2.name,"") as name,
coalesce(tab1.id,tab2.id,"") as id,
coalesce(tab1.tgt_cnt,0) as tgt_cnt,
coalesce(tab2.a_cnt,0) as a_cnt,
coalesce(tab2.b_cnt,0) as b_cnt,
coalesce(tab2.c_cnt,0) as v_cnt
from datetable t
LEFT JOIN (select * from table1) tab1 on t.d = tab1.dt
LEFT JOIN (select * from table2) tab2 on t.d = tab2.dt) a
where (tgt_cnt <> 0 or a_cnt <> 0 or b_cnt <> 0 or c_cnt <> 0);

我得到以下结果。

我的问题是记录 TOM 发生了什么。我不确定为什么 CG 和 Bob 重复两次。我的查询有问题吗。

能否请您指出为什么 TOM 记录没有进入 Left Join 以及为什么 CG 和 BOB 重复。

我期待以下结果。

非常感谢您的帮助。

谢谢,巴布

【问题讨论】:

    标签: hive hiveql hadoop2


    【解决方案1】:

    coalesce(tab1.name,tab2.name,"") as name 会将 table2 中的名称替换为 table1 中的名称,因此 TOM 从未出现,因为它被 CG 或 BOB 替换。

    我猜你想在这里实现什么......似乎你想结合 table1 和 table2。我认为完全加入是合适的。

    select * from (
    select distinct
        coalesce(t1.dt, t2.dt) as dt,
        coalesce(t1.desc, t2.desc) as desc, 
        coalesce(t1.name, t2.name) as name, 
        coalesce(t1.id, t2.id) as id,
        coalesce(t1.tgt_cnt, 0) as tgt_cnt,
        coalesce(t2.a_cnt, 0) as a_cnt,
        coalesce(t2.b_cnt, 0) as b_cnt,
        coalesce(t2.c_cnt, 0) as c_cnt
    from table1 t1
    full join table2 t2
    on t1.name = t2.name and t1.dt = t2.dt
    ) a
    where (tgt_cnt <> 0 or a_cnt <> 0 or b_cnt <> 0 or c_cnt <> 0);
    

    这将给

    dt              desc    name    id      tgt_cnt a_cnt   b_cnt   c_cnt
    6/29/2020       NULL    Tom     3       0       0       0       1
    6/29/2020       AA      CG      1       3       1       1       0
    6/29/2020       AA      Bob     2       3       0       0       0
    

    【讨论】:

    • 感谢您的回复。你说的对。合并正在用 tab1 名称覆盖 tab2 名称。我们也得到了与 FULL JOIN 相同的结果。如何将两个表数据合并到一个表中而不会丢失任何数据。
    • @Babu 这就是我的回答。我没有错过任何数据。请您再仔细阅读我的答案吗?
    • 我在 dt 字段上尝试了 FULL JOIN,因为我需要基于 dt 组合两个表。如果 dt 相同,我需要结合两个 talbes。如果它具有相同的名称,只需从一张表中获取名称。如果它是不同的名字,一个名字应该在一行中,另一个名字在下一行,以及匹配的数据
    • @Babu 我也更新了我的答案以匹配 dt。结果仍然与您的预期结果相同。
    • 知道了。它的工作完美。感谢你的快速回复。非常感谢您的帮助。
    猜你喜欢
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多