查询以根据 Athena 中两个 table 的日期获取行

Query to get rows based on dates from two table in Athena

我有两个 table,分别是 master_tbl 和 anom_table 如下:

master_tbl

 date         id     country    value     
     2017-01-01   26      US        2            
     2017-01-02   26      US        4             
     2017-01-03   26      US        9             
     2017-01-04   26      US        2             
     2017-01-05   26      US        4             
     2017-01-06   26      US        1
     2017-01-07   26      US        5
     2017-01-08   26      US        3
     2017-01-09   26      US        100
     2017-01-10   26      US        4 

anom_tbl

date         id  country     anoms
 2017-01-01   26      US        0
 2017-01-02   26      US        0
 2017-01-03   26      US        9
 2017-01-04   26      US        0
 2017-01-05   26      US        0
 2017-01-06   26      US        0
 2017-01-07   26      US        0
 2017-01-08   26      US        0
 2017-01-09   26      US        100
 2017-01-10   26      US        0

我想从 master_tbl 创建第三个 table 并与 anom_tbl 连接到 select 只有日期在 [=34 的 anom 列中具有值的行=] 以及该日期的前一天和后一天从 master_tbl

最后想要的是下面的table

date         id  country     value
 2017-01-02   26      US        2
 2017-01-03   26      US        9
 2017-01-04   26      US        4
 2017-01-08   26      US        3
 2017-01-09   26      US        100
 2017-01-10   26      US        4

因为我有大数据,所以我需要时间在 R 中 运行 或 python 然后我想在 AWS (athena)

中创建 table

我已经在 athena 中尝试了以下代码,但是它不起作用

FROM 
    (SELECT t2.value,
         t1.id,
         t1.country AS country,
         cast(t1.date AS DATE) AS orig_date
    FROM 
        (SELECT id,
         country,
         date
        FROM anom_tbl) t1
        JOIN master_tbl t2
            ON t2.id=t1.id
                AND t2.country= t1.country
                AND t2.date=t1.date) t3
    JOIN master_tbl t2
    ON t3.id=t2.id
        AND t3.country=t2.country 
        where t2.date IN(GETDATE()-1)  

能否请您帮我修改 sql 代码以获得正确的结果。

如果我没看错,你可以用exists:

select m.*
from master_tbl m
where exists (
    select 1
    from anom_tbl a
    where 
        a.anoms <> 0
        and a.id = m.id 
        and a.country = m.country
        and m.date >= a.date - interval '1' day
        and m.date <= a.date + interval '1' day
)

这会带来主 table 中的所有记录,在 anom table 中存在另一条记录,具有相同的 ID 和国家,具有非 0 值,在 +/- 1 内天间隔。