title: First and last value of window function in one row in PostgreSQL
body: <p>I'd like to have first value of one column and last value of second column in one row for a specified partition. For that I created this query:</p>
  
  <pre><code>SELECT DISTINCT
  b.machine_id,
  batch,
  timestamp_sta,
  timestamp_stp,
  FIRST_VALUE(timestamp_sta) OVER w AS batch_start,
  LAST_VALUE(timestamp_stp) OVER w AS batch_end
  FROM db_data.sta_stp AS a
  JOIN db_data.ll_lu AS b
  ON a.ll_lu_id=b.id
  WINDOW w AS (PARTITION BY batch, machine_id ORDER BY timestamp_sta)
  ORDER BY timestamp_sta, batch, machine_id;
  </code></pre>
  
  <p>But as you can see in the image, returned data in batch_end column are not correct.</p>
  
  <p><em>batch_start</em> column has correct first value of <em>timestamp_sta</em> column. However <em>batch_end</em> should be "2012-09-17 10:49:45" and it equals <em>timestamp_stp</em> from same row.</p>
  
  <p>Why is it so?</p>
  
  <p><a href="https://i.stack.imgur.com/h3DuF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/h3DuF.png" alt="enter image description here"></a></p>