title: PostgreSQL use value from previous row if missing
body: <p>I have a following query:</p>
  
  <pre><code>WITH t as (
    SELECT date_trunc('hour', time_series) as trunc 
    FROM generate_series('2013-02-27 22:00'::timestamp, '2013-02-28 2:00', 
                         '1 hour') as time_series
    GROUP BY trunc
    ORDER BY trunc
  )
  SELECT DISTINCT ON(trunc) trunc, id
  FROM t
  LEFT JOIN (
     SELECT id, created, date_trunc('hour', created) as trunc_u
     FROM event
     ORDER BY created DESC
  ) u
  ON trunc = trunc_u
  </code></pre>
  
  <p>which yields the following result:</p>
  
  <pre><code>"2013-02-27 22:00:00";
  "2013-02-27 23:00:00";2
  "2013-02-28 00:00:00";5
  "2013-02-28 01:00:00";
  "2013-02-28 02:00:00";
  </code></pre>
  
  <p>Table <code>event</code> has <code>id</code>, <code>created</code> and some other columns, but only those are relevant here. The query above gives me <code>id</code> of last event generated per given <code>trunc</code> time period (thanks to <code>DISTINCT ON</code> I get a nice aggregation per period).</p>
  
  <p>Now, this query yields <code>NULL</code> if no events happened in given time period. I would like it to return the previous available <code>id</code>, even if it is from different time period. I.e.:</p>
  
  <pre><code>"2013-02-27 22:00:00";0
  "2013-02-27 23:00:00";2
  "2013-02-28 00:00:00";5
  "2013-02-28 01:00:00";5
  "2013-02-28 02:00:00";5
  </code></pre>
  
  <p>I am sure I am missing some easy way to accomplish this. Any advice?</p>