大查询:当 1 table 包含用户 ID 数组时,如何在用户 ID 上加入 2 table?

Big Query: How to join 2 tables on user ID when 1 table contains an array of user ids?

Whosebug 上已经发布了一些类似的答案,但他们没有解决这个具体案例或涉及我无法理解的查询,因为我刚刚开始我的第一个 SQL-related位置。

这是我第一次尝试以数组形式连接其中一个表中具有列值的表。在尝试解决我自己的问题后,我 运行 出现以下错误:No matching signature for operator = for argument types: ARRAY<INT64>, STRING.

我有 2 个表如下所示:

Table 1:

team_id     user_id
   1       [1, 2, 3]
   2       [4, 5, 6]
   3       [7, 8, 9]
   4      [10, 11, 12]

Table 2:

user_id    value
   2         10
   5         20
   7         30
   12        40

我想加入 Table 2 到 Table 1 通过 Table 2 分析 user_id 数组中是否有匹配 [=] 34=] 1.如果有,则根据commonuser_id加入,输出结果如下:

期望的输出

team_id  user_id  value
1          2       10
2          5       20
3          7       30
4          12      40

提前感谢您分享您的知识!

您可以加​​入 unnest():

select t1.team_id, t2.user_id, t2.value
from table1 t1
inner join table2 t2 on t2.user_id in unnest(t1.user_id)

以下适用于 BigQuery 标准 SQL

#standardSQL
SELECT team_id, 
  ARRAY_AGG(t2.user_id IGNORE NULLS) user_id,
  IFNULL(SUM(value), 0) value
FROM `project.dataset.table1` t, t.user_id AS user_id
LEFT JOIN `project.dataset.table2` t2
USING(user_id)
GROUP BY team_id

您可以使用与您的相关样本数据类似的样本数据进行测试,如以下示例所示

#standardSQL
WITH `project.dataset.table1` AS (
  SELECT 1 team_id, [1, 2, 3] user_id UNION ALL
  SELECT 2, [4, 5, 6] UNION ALL
  SELECT 3, [7, 8, 9] UNION ALL
  SELECT 4, [10, 11, 12] UNION ALL
  SELECT 5, [13, 14]
), `project.dataset.table2` AS (
  SELECT 2 user_id, 10 value UNION ALL
  SELECT 3, 20 UNION ALL
  SELECT 5, 20 UNION ALL
  SELECT 7, 30 UNION ALL
  SELECT 9, 1 UNION ALL
  SELECT 12, 40 
)
SELECT team_id, 
  ARRAY_AGG(t2.user_id IGNORE NULLS) user_id,
  IFNULL(SUM(value), 0) value
FROM `project.dataset.table1` t, t.user_id AS user_id
LEFT JOIN `project.dataset.table2` t2
USING(user_id)
GROUP BY team_id    

有输出