title: Comparing different rows in PostgreSQL for each Id
body: <p>Few columns in my table looks like</p>
  
  <pre><code>Id   Code   date        latest
  1    T     2014-10-04    0
  2    B     2014-10-19    0
  2    B     2014-10-26    0
  1    S     2014-10-05    0
  1    T     2014-10-06    0
  1    T     2014-10-08    1
  2    P     2014-10-27    1
  </code></pre>
  
  <p>I am tracking all changes made by each ID. if there is any change, I insert new row and update the latest value column.</p>
  
  <p>What I want is for each Id, I should be able to find last code where latest is 0. Also, that code should not be equal to existing code(latest = 1) So for id = 1, answer cannot be </p>
  
  <pre><code> Id   Code
   1    T
  </code></pre>
  
  <p>as for <code>id = 1</code> T is existing code (<code>latest = 1</code>).<br>
  So ideally my output should look like:</p>
  
  <pre><code>Id    Code
   1     S
   2     B
  </code></pre>
  
  <p>I think I can get the latest value for code for each id where <code>latest = 0</code>.</p>
  
  <p>But how do I make sure that it should not be equal to existing code value (<code>latest = 1</code>)</p>