hive - Hive 中的左连接未返回预期结果
问题描述
我有 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 重复出现。
非常感谢您的帮助。
谢谢,巴布
解决方案
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
推荐阅读
- children - 跟踪 AMI 后代的最佳方法是什么?
- android - 工具栏不允许在其中使用匹配父布局
- java - 使用滑块方法浏览大量图像
- azure-gov - 公共云中的应用程序是否可以被授权通过图形 api 从政府租户获取数据?
- azure - 接收者未收到 Mass Transit 的消息 - 订阅
- java - Java SpringBoot Postgres 删除行
- r - 使用 case_when 在内部发生变异
- python - Selenium 如何选择正文中的最后一个链接?
- python - 如何在不使用 Python 绘图的情况下检测季节性
- php - 帮助理解和解决我的 WordPress index.php 中的恶意代码