PostgreSQL use value from previous row if missing

前端 未结 2 522
醉梦人生
醉梦人生 2020-12-19 17:12

I have a following query:

WITH t as (
  SELECT date_trunc(\'hour\', time_series) as trunc 
  FROM generate_series(\'2013-02-27 22:00\'::timestamp, \'2013-02-         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 17:57

    You ca mix a self join and windows functions

    Simplifying I take this table with this sample values:

    create table t ( a int, b int);    
    insert into t values 
    ( 1, 1),
    ( 2, Null),
    ( 3, Null),
    ( 4, 2 ),
    ( 5, Null),
    ( 6, Null);
    

    In your query a is trunc_u and b is your id. The query is:

    with cte as (    
        select 
          t1.a, 
          coalesce( t1.b, t2.b, 0) as b,
          rank() OVER 
           (PARTITION BY t1.a ORDER BY t2.a DESC) as pos
        from t t1 
        left outer join t t2
          on t2.b is not null and
             t2.a < t1.a    
    )
    select a, b
    from cte
    where pos = 1;
    

    And results:

    | A | B |
    ---------
    | 1 | 1 |
    | 2 | 1 |
    | 3 | 1 |
    | 4 | 2 |
    | 5 | 2 |
    | 6 | 2 |
    

提交回复
热议问题