首页 > 解决方案 > 在 sql 中使用 LAG 跳过特定行

问题描述

我有一个看起来像这样的表:

在此处输入图像描述

使用 SQL 中的 LAG 函数,我想仅对 star_date=end_date 的值执行 LAG,并获取过去的 start_date 记录,其中 start_date=end_date。我的茶几会有一个额外的列,如下所示: 在此处输入图像描述

我希望我的问题很清楚,任何帮助表示赞赏。

标签: sqlgoogle-bigquerylagskip

解决方案


您可以为这些值分配一个组并使用它:

select t.*,
       (case when start_date = end_date
             then lag(start_date) over (partition by (case when start_date = end_date then 1 else 0 end) order by start_date)
        end) as prev_eq_start_date
from t;

或者:

select t.*,
       (case when start_date = end_date
             then lag(start_date) over (partition by start_date = end_date order by start_date)
        end) as prev_eq_start_date
from t;

请注意,如果您的数据很大并且大多数行的日期不同,那么您可能会遇到资源问题。在这种情况下,一个额外的未使用的partition by密钥可以帮助:

select t.*,
       (case when start_date = end_date
             then lag(start_date) over (partition by (case when start_date = end_date then 1 else 2 end), (case when start_date <> end_date then start_date end) order by start_date)
        end) as prev_eq_start_date
from t;

这对结果没有影响,但它可以避免由于具有不同值的行太多而导致的资源错误。


推荐阅读