首页 > 解决方案 > 需要在hive中查找同一张表的数据差异

问题描述

我有一个加载了时间戳列的历史表。我需要使用时间戳列获取减去的数据。逻辑:通过(loaded_timestamp -1)和current_timestamp减去数据得到email地址。只有减去的数据应该是输出。

选择查询:

select t1.email_addr
from (select *
      from table t1
      where loaded_timestamp = current_timestamp
     ) left outer join
     (select *
      from table t2
      where loaded_timestamp = date_sub(current_timestamp,1)
    )
where t1.email!=t2.email;

表有以下列

Email address, First name , last name, loaded_timestamp. 
xxx@gmail.com,xxx,aaa,2020-03-08.   
yyy@gmail.com,yyy,bbb,2020-03-08. 
zzz@gmail.com,zzz,ccc,2020-03-08. 
xxx@gmail.com,xxx,aaa,2020-03-09. 
yyy@gmail.com,yyy,bbb,2020-03-09.

期望的结果

zzz@gmail.com

因此,如果从同一张表中减去两个日期,即(2020-03-09 - 2020-03-08)。我应该只得到不匹配的记录。匹配的记录应该被丢弃,不匹配的记录应该是输出。

标签: sqlhive

解决方案


我能想到的最好的办法是你想要只出现一次的电子邮件。如果是这种情况,请使用窗口函数:

select t.*
from (select t.*, count(*) over (partition by email) as cnt
      from t
     ) t
where cnt = 1;

如果您想要数据中的电子邮件但未在当前日期加载,则:

select t.email
from t
group by t.email
having max(timestamp) <> current_date;

推荐阅读