我正在努力实现SQL查询,以根据分组方案从2个HIVE表中识别丢失的记录。数据如下
表1-日历
month_last_day
20190131
20190229
20190331
20190430
表2-项目
itemid date
101 20190131
101 20190229
101 20190331
102 20190131
102 20190331
102 20190430
上表中的日历是一个包含所有日期的主表,“项目”表包含不同项目ID的数据,而缺少主表中的某些日期。例如,itemid 101缺少日期20190430,而102缺少日期20190229。
我需要输出以2行显示为101 20190430,另一行显示102 20190229。
我尝试了正确的外部联接,存在一些概念,但是没有任何作用,因为需要对分组记录进行过滤。请提出建议。
答案 0 :(得分:1)
cross join
日历以显示不同的项目,并left join
列出项目表以获取缺失的行。
select i.itemid,c.month_last_day
from calendar c
cross join (select distinct itemid from items) i
left join items it on it.itemid = i.itemid and c.month_last_day = it.dt
where it.dt is null
答案 1 :(得分:0)
使用交叉联接和左外部联接在蜂巢中查询。
with calendar as
(select '20190131' last_day union all
select '20190229' last_day union all
select '20190331' last_day union all
select '20190430'
)
,items as
(select 101 itemid,'20190131' dt union all
select 101 itemid,'20190229' dt union all
select 101 itemid,'20190331' dt union all
select 102 itemid,'20190131' dt union all
select 102 itemid,'20190331' dt union all
select 102 itemid,'20190430' dt
),
res1 as
(select i.itemid, c.last_day from calendar c, (select distinct itemid from items) i)
select res1.itemid, res1.last_day from res1 left outer join items i on res1.itemid = i.itemid and res1.last_day=i.dt where i.dt is null;