与两个表 BigQuery 中的 ID 关联的所有值的滚动总和
Rolling sum of all values associated with the ids from two tables BigQuery
我在 BigQuery 中有两个 table。一个 table 有 date
、id
和 name
列。对于每个名称,都有几个与之关联的 ID。数据如下所示:
date id name
7/11 1 A
7/11 2 A
7/11 3 B
7/11 4 B
另一个 table 中有 date
、id
、comments
、shares
列。 table 中的 id
没有与之关联的名称。 table 看起来像这样:
date id comments shares
7/11 1 2 null
7/11 2 4 2
7/11 3 1 1
7/11 4 5 3
最终目标是获取与特定名称 (table 1) 相关联的所有 ID,并总结该名称或 ID 列表的评论和分享 (table 2)
所需的输出看起来像这样:
date name comments shares
7/11 A 6 2
7/11 B 6 4
您需要连接 2 个表和聚合:
SELECT t1.date, t1.name,
COALESCE(SUM(t2.comments), 0) comments,
COALESCE(SUM(t2.shares), 0) shares
FROM table1 t1 LEFT JOIN table2 t2
ON t2.date = t1.date AND t2.id = t1.id
GROUP BY t1.date, t1.name
参见demo。
我在 BigQuery 中有两个 table。一个 table 有 date
、id
和 name
列。对于每个名称,都有几个与之关联的 ID。数据如下所示:
date id name
7/11 1 A
7/11 2 A
7/11 3 B
7/11 4 B
另一个 table 中有 date
、id
、comments
、shares
列。 table 中的 id
没有与之关联的名称。 table 看起来像这样:
date id comments shares
7/11 1 2 null
7/11 2 4 2
7/11 3 1 1
7/11 4 5 3
最终目标是获取与特定名称 (table 1) 相关联的所有 ID,并总结该名称或 ID 列表的评论和分享 (table 2) 所需的输出看起来像这样:
date name comments shares
7/11 A 6 2
7/11 B 6 4
您需要连接 2 个表和聚合:
SELECT t1.date, t1.name,
COALESCE(SUM(t2.comments), 0) comments,
COALESCE(SUM(t2.shares), 0) shares
FROM table1 t1 LEFT JOIN table2 t2
ON t2.date = t1.date AND t2.id = t1.id
GROUP BY t1.date, t1.name
参见demo。