Sql 通过分组查找丢失的记录

Sql 通过分组查找丢失的记录,sql,hive,impala,Sql,Hive,Impala,我正在努力实现SQL查询,以便根据分组场景从2个配置单元表中识别丢失的记录。数据如下 表1-日历 month_last_day 20190131 20190229 20190331 20190430 表2-项目 itemid date 101 20190131 101 20190229 101 20190331 102 20190131 102 20190331 102 20190430 上表中的日历是一个主表,包含所有日期,而Items表包含不同ite

我正在努力实现SQL查询,以便根据分组场景从2个配置单元表中识别丢失的记录。数据如下

表1-日历

month_last_day
20190131
20190229
20190331
20190430

表2-项目

itemid date
101    20190131
101    20190229
101    20190331
102    20190131
102    20190331
102    20190430
上表中的日历是一个主表,包含所有日期,而Items表包含不同item id的数据,主表中的某些日期与此对应。例如,itemid 101缺少日期20190430,而102缺少日期20190229

我需要的输出,呈现为101 20190430和另一行102 20190229两行


我已经尝试了正确的外部连接,但没有任何效果,因为需要对分组记录进行过滤。请建议。

交叉连接
日历到不同的项目,并
左连接
项目表以获取缺少的行

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 

在配置单元中使用交叉联接和左外部联接进行查询

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;

你用的是什么产品?“SQL”只是一种查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加标记,
postgresql
oracle
db2
sql server
,…配置单元表上的Impala sql看起来join没有生成值为null的日期记录。这是我的主要问题。不知道为什么不知道你在说什么。请看这里的一个工作示例,不知何故,left join在我的例子中并没有帮助,但当我用“where not exists”子句替换它时,它工作了。感谢您提出交叉连接概念。它确实帮助了我。再次感谢,