title: postgresql: last occurred value of id x for a given id y in a table
body: <p>Hi  I'm new to postgresql and need a little help.</p>
  
  <p>i have the following table, where rows belong to class 1 or 2 based on the value of column pf. The rows are ordered by charttime. </p>
  
  <p><a href="http://i.stack.imgur.com/uBxRs.png" rel="nofollow">table</a></p>
  
  <p>i want a new column called prev_val, and the prev_val corresponding row should be equal to the last occurring value of the the class diff from the corresponding rows class. i.e. ex- if pf=2 for a given row then the prev_val of this row must be equal to the previous value of a row with pf=1.   </p>
  
  <p>i.e. </p>
  
  <p>for a given pf=2, prev_val=valuenum of pf=1 with charrttime less than current row</p>
  
  <p>for a given pf=1, prev_val=valuenum of pf=2 with charrttime less than current row</p>