sql - 雪花中实现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
这也相当复杂和耗时。
还有其他建议吗?
解决方案
你可以使用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 1
在row_number()
窗口函数中使用来提高效率。
推荐阅读
- git - 如何从 GCP 中的 gerrit 容器中克隆项目?
- azure - 用于资产位置跟踪的 Azure 存储架构设计
- express - 在 Express 中 res.send 后处理异步调用有什么问题
- java - 为什么我的变量在这种方法中都消失了?
- python - django Helpdesk Web 应用程序中的聊天功能
- vue.js - 如何在 v-for 循环中单独呈现所选的类
- flutter - 版本更改后,英雄小部件不能是另一个英雄小部件的后代
- r - 将不同函数的参数传递给 R 函数
- c# - 从另一个应用程序打开应用程序,同时能够与其代码交互
- pandas - 通过对 Pandas 中的某些列求和来组合多个数据框