title: SQL select value if no corresponding value exists in another table
body: <p>I have a database which tries to acheive point-in-time information by having a master table and a history table which records when fields in the other table will/did change. e.g.</p>
  
  <p><strong>Table: Employee</strong></p>
  
  <pre><code>Id  | Name      | Department
  -----------------------------
  0   | Alice     | 1
  1   | Bob       | 1
  </code></pre>
  
  <p><strong>Table: History</strong></p>
  
  <pre><code>ChangeDate   | Field      | RowId  | NewValue    
  ---------------------------------------------
  05/05/2009   | Department | 0      | 2
  </code></pre>
  
  <p>That records that employee 0 (Alice) will move to department 2 on 05/05/2009.</p>
  
  <p>I want to write a query to determine the employee's department on a particular date. So it needs to:</p>
  
  <ul>
  <li>Find the first history record for that field and employee <em>before</em> given date</li>
  <li>If none exists then default to the value currently in the master employee table.</li>
  </ul>
  
  <p>How can I do this? My intuition is to select the first row of a result set which has all suitable history records reverse ordered by date and with the value in the master table last (so it's only the first result if there are no suitable history records), but I don't have the required SQL-fu to achieve this.</p>
  
  <hr>
  
  <p><em>Note: I am conscious that this may not be the best way to implement this system - I am not able to change this in the short term - though if you can suggest a better way to implement this I'd be glad to hear it.</em></p>