我有兩個表。一個是元資料,一個是計費資料。我需要有效地連接這些表,以便將元資料分配給費用。
表1(元資料)看起來是這樣的:
年 月 日 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
表2(帳單資料)看起來像這樣:
年 月 id cost
2021 06 892221805 1.00$
2021 06 892221805 1.00 $
2021 06 594083437 1.00 $
2021 06 552604244 1.00 $
對于表2中的每一個年、月、ID的組合,在表1中都有一個相應的ID。
對于T2中的每一個年、月、ID,我需要從T1中符合年、月、ID并具有最高日期(在該月)的行中獲得label1和label2,這樣,結果可能看起來像這樣:
年 月 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兼容。
我如何正確選擇?最好是以一種可以用作視圖的方式。
uj5u.com熱心網友回復:
你可以使用row_number()來獲取一個月的最后一行:
select t2.*, t1.label1, t1.label2
from table2 t2 left join
(select t1.*)
row_number() over (partition by year, 月, id 順序 by 日 desc) as seqnum
from table1 t1
) t1
on t1.id = t2.id and t1.year = t2.yearand
t1.month = t2.month and seqnum = 1。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/322155.html
標籤:
上一篇:回傳具有多個值之一的行
