【问题标题】:How can I extract the values of the last aggregation date in sql如何在sql中提取最后一个聚合日期的值
【发布时间】:2020-02-20 21:14:54
【问题描述】:

我有下表。

id  user    time_stamp                 
1   Mike    2020-02-13 00:00:00 UTC     
2   John    2020-02-13 00:00:00 UTC      
3   Levy    2020-02-12 00:00:00 UTC      
4   Sam     2020-02-12 00:00:00 UTC      
5   Frodo   2020-02-11 00:00:00 UTC      

假设 2020-02-13 00:00:00 UTC 是最后一天,我想查询此表以仅显示最后一天的结果?我想在 Bigquery 中创建一个视图,以便我始终只获得最后一天的结果?

所以最后我得到了这样的东西(最后一天是 2020-02-13 00:00:00 UTC)

id  user    time_stamp                 
1   Mike    2020-02-13 00:00:00 UTC     
2   John    2020-02-13 00:00:00 UTC           

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    你可以使用窗口函数:

    select t.* except (seqnum)
    from (select t.*,
                 dense_rank() over (order by time_stamp) as seqnum
          from t
         ) t
    where seqnum = 1;
    

    这可能不适用于大量数据——因为 BQ 在没有分区的情况下实现窗口函数的方式。因此,您可能会发现这样效果更好(尤其是在上述资源耗尽的情况下):

    select t.*
    from t join
         (select max(time_stamp) as max_time_stamp
          from t
         ) tt
         on t.time_stamp = max_time_stamp;
    

    此外,如果时间戳实际上包含日期组件,那么您需要转换为 date 或以某种方式删除时间组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-14
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 2022-01-18
      • 2021-04-16
      相关资源
      最近更新 更多