如何在仅从一个 table 中选择每个月的最高日的同时加入两个 table

How to join two tables while only selecting the highest day of each month from one table

我有两张桌子。一种带有元数据,一种带有计费数据。我需要有效地加入这些以便将元数据分配给成本。

Table 1(元数据)如下所示:

year    month   day id          label1     label2
2021    06      04  892221805   foo        aaa
2021    06      30  892221805   bar        aaa     
2021    06      04  594083437   baz        aaa
2021    06      04  552604244   baz        bbb

Table 2(帐单数据)如下所示:

year    month   id          cost
2021    06      892221805   1.00 $
2021    06      892221805   1.00 $    
2021    06      594083437   1.00 $
2021    06      552604244   1.00 $

Table2中每一个年月id的组合,在Table1中都有对应的ID。

对于 T2 中的每个年、月、id,我需要 T1 中匹配年、月、id 并且具有最高日期(那个月)的行中的 label1、label2,以便结果看起来像这样:

year    month   id          cost   label1 label2
2021    06      892221805   1.00 $ bar    aaa
2021    06      892221805   1.00 $ bar    aaa
2021    06      594083437   1.00 $ baz    aaa
2021    06      552604244   1.00 $ baz    bbb

即未使用 T1 的第一行,因为第二行的标签具有该月较新的日期。

我在 Amazon Webservices 上使用 Atheana,我认为它应该与 Presto 兼容。

我如何 select 正确?最好以一种可以用作视图的方式。

您可以使用 row_number() 到达一个月的最后一行:

select t2.*, t1.label1, t1.label2
from table2 t2 left join
     (select t1.*
             row_number() over (partition by year, month, id order by day desc) as seqnum
      from table1 t1
     ) t1
     on t1.id = t2.id and t1.year = t2.year and
        t1.month = t2.month and seqnum = 1;