【问题标题】:Compare current value with previous and list the results if meet criteria将当前值与以前的值进行比较,如果符合条件则列出结果
【发布时间】:2025-12-05 06:00:01
【问题描述】:

我有一个由Timestamplocationmetric 组成的原始表。我想生成另一个表,其中仅输出当前行低于上一行的 40% 的行以及上一条记录之间的percentage 差异。

输入示例

Timestamp location metric
2021-10:00:00 Dallas 150
2021-10:05:00 Dallas 120
2021-10:10:00 Dallas 180
2021-10:15:00 Dallas 100
2021-10:20:00 Dallas 59
2021-10:25:00 Dallas 100

预期输出

Timestamp location metric percentage
2021-10:15:00 Dallas 100 56%
2021-10:20:00 Dallas 59 59%

【问题讨论】:

    标签: mysql sql google-bigquery


    【解决方案1】:

    我想你想要lag():

    select t.*, metric / prev_metric as ratio
    from (select t.*,
                 lag(metric) over (partition by location order by timestamp) as prev_metric
          from t
         ) t
    where metric < 0.4 * prev_metric ;
    

    【讨论】:

      【解决方案2】:

      考虑下面

      select * from (
        select *, round(100 * metric / lag(metric) over win, 0) calc
        from `project.dataset.table`
        window win as (partition by location order by timestamp)
        )
      where calc < 60      
      

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

      注意:我相信您的示例数据在时间戳值中有拼写错误 - 最后几行都有 2021-10:15:00 值,所以我认为这是一个拼写错误 - 因此在您的问题中修复了它

      【讨论】: