【问题标题】:bigquery left join by closest previous valuebigquery 通过最接近的先前值左连接
【发布时间】:2020-11-26 12:42:07
【问题描述】:

我有两张表如下:

表_1:

timestamp                id
2020-11-24 01:05:00 UTC  AA
2020-11-24 01:07:00 UTC  AA
2020-11-24 01:07:00 UTC  BB

表_2:

timestamp                id   covered
2020-11-24 01:04:00 UTC  AA   true
2020-11-24 01:06:00 UTC  AA   false

我想向 table_1 添加一列以显示 table_2 中的覆盖值。虽然时间戳不匹配,但我想获取 table_2 中捕获的最接近的先前时间戳。 例如,AA 在 1:04 被覆盖,在 1:06 被覆盖,因此结果表如下所示:

timestamp                id   covered
2020-11-24 01:05:00 UTC  AA   true
2020-11-24 01:07:00 UTC  AA   false
2020-11-24 01:07:00 UTC  BB   null

你能帮我完成这个查询吗:

SELECT TABLE_1.timestamp, TABLE_1.id, TABLE_2.covered 
FROM TABLE_1 
LEFT JOIN 
TABLE_2
ON TABLE_1.id = TABLE_2.id
AND ?

【问题讨论】:

    标签: sql join google-bigquery left-join


    【解决方案1】:

    BigQuery 对非等值连接并不感兴趣。所以另一种选择是使用union all 和一些技巧:

    select t12.*
    from (select t12.*,
                 last_value(covered ignore nulls) over (partition by id order by timestamp) as imputed_covered
          from ((select timestamp, id, null as covered
                 from table_1
                ) union all
                (select timestamp, id, covered
                 from table_2
                )
               ) t12
         ) t12
    where covered is null; 
    

    这是合并两个表。然后last_value() 检索最新的covered 值——对于table_1 行将来自table_2

    最后的where 只是将结果集过滤为只有table_1 行。

    【讨论】:

      猜你喜欢
      • 2017-11-06
      • 2015-11-29
      • 2012-09-26
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      相关资源
      最近更新 更多