PostgreSQL use value from previous row if missing

前端 未结 2 505
醉梦人生
醉梦人生 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:56

    Try:

    WITH t as (
      SELECT time_series as trunc 
        FROM generate_series('2013-02-27 22:00'::timestamp, '2013-02-28 2:00', 
                             '1 hour') as time_series
    )
    SELECT DISTINCT ON(t.trunc) t.trunc, e.id
      FROM t
      JOIN event e
        ON e.created < t.trunc 
     ORDER BY t.trunc, e.created DESC
    

    If it is too slow - tell me. I will give you a faster query.

    0 讨论(0)
  • 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 |
    
    0 讨论(0)
提交回复
热议问题