sql - 在 Big Query 中制作连接表数组的最佳方法是什么?
问题描述
我正在尝试使用 SQL 在 Big Query 中进行一些数据转换。
假设我有三个表:
客户 - 有关客户的数据,例如年龄等 订阅 - 有关用户订阅的数据 参与度 - 有关客户如何与数字产品交互的数据。
我想使用嵌套字段将其收集在一个表中。
我可以加入所有这些表,但我想将它们聚合到数组中。
因此,我得到的不是三个表:
id:123,
name:David,
age:30,
subscritions: [{
name:sub1
price:10
},
{
name:sub2
price:20
}],
engagment: [{
event:visited_product_x
time:2020-06-10
},
{
event:visited_product_y
time:2020-06-10
}]
当然,我在 SELECT 中使用了 array_agg。当只添加一个表时,效果很好。但是,当添加另一个时,我会得到重复的行,这是我不想要的。所以,我想我不应该在 SELECT 中使用 array_agg,而应该在其他地方使用。
但是解决这个问题的最佳方法是什么?
解决方案
您可以使用子查询来构造字段。像这样的东西:
select c.*,
(select array_agg(s)
from substriptions s
where s.user_id = c.user_id
) as subscriptions,
(select array_agg(e)
from engagements e
where e.user_id = c.user_id
) as engagements
from customers c
推荐阅读
- python - cross_val_score 与 sklearn 中的不同分类器的行为不同
- mongodb - 如何在 MongoDB 中将我的所有文本 _id 字段从“abc”更新为“xxx#abc”
- ios - Firebase Google 登录获取凭据
- java - 如何指定数组应从扫描仪接受哪些数字
- python - 结合 GridSearchCV 和 StackingClassifier
- python - 用于构建自动编码器的 keras.Flatten 的逆
- java - 无法在 Java 程序上得到想要的结果
- python - 如何使用 python 的 plotly express 将多个图形添加到单个选项卡
- javascript - 我们可以像在 Vue 中一样在 Polymer 中使用模板语法吗?
- aws-lambda - 为什么即使在删除 cloudwatch 事件之后,aws lamba 也会在间隔后继续执行?