首页 > 解决方案 > 雪花中实现sql“JOIN”返回策略的最佳实践

问题描述

假设我们有两个执行左连接的表:

表格1

Joint Key  || Attribute 1 || Attribute 2 || Attribute 3
   A             1               11           21        
   B             2               12           22
   C             3               13           23

表 2

Joint Key  || Attribute 4 || Attribute 5 
   A             31               41      
   A             32               42      
   C             33               43    

通过在“联合键”上执行表 1左连接表 2,它将返回两条记录 Joint Key = 'A'

Joint Key  || Attribute 1 || Attribute 2 || Attribute 3 || Attribute 4 || Attribute 5 
   A             1               11           21              31               41    
   A             1               11           21              32               42  

定义返回警察的最佳做法是什么,特别是在雪花中,可以返回与表 1相同的行数。

以上面的例子为例,我希望记录有MAX(Attribute 4). 我想到了两个初步的想法

选项 1:使用“GROUP BY”子句——需要明确列出列,处理有很多列的表时很麻烦。

选项2:类似

select * from (
  select 
    Tabel1.*
    max(Table2.Attribute_4) as mx_Attribute_4,
    Table2.Attribute_5
 from Table1
 left join Table2
 on Joint_Key
) as temp
where temp.Attribute_4 = temp.mx_Attribute_4

这也相当复杂和耗时。

还有其他建议吗?

标签: sqltsqlsnowflake-cloud-data-platform

解决方案


你可以使用QUALIFY

就像是:

select
    t1.Joint_key, t1.Attribute_1, t1.Attribute_2, t1.Attribute_3, t2.Attribute_4, t2.Attribute_5
from Table1 t1
left join Table2 t2
    on t1.Joint_key = t2.Joint_key
qualify row_number() over(partition by Joint_Key order by Attribute_4 desc) = 1

这当然更干净,并且应该比 group by 更有效。它仍然需要查询按 Attribute_4 对记录进行排序,但我看不到避免这种情况的方法,除非您可以使用任何一组值而不是具有 MAX(Attribute_4) 的值集。在这种情况下,您可以通过order by 1row_number()窗口函数中使用来提高效率。


推荐阅读