【问题标题】:Find nearest prior row with specific condition查找具有特定条件的最近的前行
【发布时间】:2022-01-15 04:35:31
【问题描述】:

假设我有下表:

id column B
1 value A
2 value B
3 value D
4 value C
5 value D
6 value D
7 value D
8 value E
9 value F
10 value D

对于值为 D 的每一行,我需要找到与 D 不同的值的最近的上一行。所以我需要的是:

id nearest row id
1 null
2 null
3 2
4 null
5 4
6 4
7 4
8 null
9 null
10 9

如何在 PostreSQL 中实现这一点?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    理想情况下,这应该通过LAG() IGNORE NULLS (...) 完成,但 PostgreSQL 不支持它。解决方法是认为除value d 之外的每个值都启动一个组,然后在整个组中复制所需的值:

    with cte1 as (
        select *, case when b = 'value d' then null else id end as grp_id
        from t
    ), cte2 as (
        select *, sum(case when grp_id is not null then 1 end) over (order by id) as grp_num
        from cte1
    )
    select *, case when b = 'value d' then max(grp_id) over (partition by grp_num) end as nearest_row_id
    from cte2
    

    DB<>Fiddle

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 2022-08-13
      • 2014-04-02
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      相关资源
      最近更新 更多