【问题标题】:SQL(BigQuery) Join two tables with lag() functionSQL(BigQuery) 使用 lag() 函数连接两个表
【发布时间】:2021-02-21 17:50:43
【问题描述】:

考虑到我有两张桌子。

第一个:

user_id name timestamp1
1 purchase 12
1 purchase 14
2 purchase 22
2 purchase 14

第二个:

user_id event_name timestamp2
1 event1 10
1 event2 11
2 event12 20
2 event10 12

A 想要将表 2 中的一些字段(event_name,timestamp2)添加到表 1 中,这些字段(event_name,timestamp2)与 user_id 最接近的先前值,按表 1 中每个事件的时间戳排序

所需的表应如下所示

user_id name timestamp1 event_name timestamp2
1 purchase 12 event2 11
1 purchase 14 event2 11
2 purchase 22 event12 20
2 purchase 14 event10 12

请帮我查询一下sql! 谢谢。

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    您可以在user_id 上使用连接,然后使用row_number()timestamp1timestamp2 之间的距离排序以从table2 中获取最近的行:

    SELECT  user_id, name, timestamp1, event_name, timestamp2
    FROM (
      SELECT    t1.*, t2.event_name, t2.timestamp2,
                ROW_NUMBER() OVER(PARTITION BY t1.user_id, t1.timestamp1 ORDER BY ABS(t1.timestamp1 - t2.timestamp2)) AS rn
      FROM      table1 t1
      INNER JOIN table2 t2
      ON        t1.user_id = t2.user_id 
    )
    WHERE rn = 1
    

    输出:

    【讨论】:

      【解决方案2】:
      select any_value(t1).*, 
        array_agg(struct(event_name,timestamp2) order by timestamp2 desc limit 1)[offset(0)].*
      from `project.dataset.table1` t1 
      cross join `project.dataset.table2` t2
      where t2.user_id = t1.user_id and timestamp2 < timestamp1
      group by format('%t', t1)    
      

      如果应用于您问题中的样本数据 - 输出是

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-11
        • 1970-01-01
        • 2022-01-15
        • 2018-10-17
        • 1970-01-01
        • 2012-02-28
        • 2012-05-01
        相关资源
        最近更新 更多