title: SQL: How to select only distinct rows based on some property values
body: <p>I have an sql-view in my database which uses a UNION to concat different results (one side contains a left join whereas the other side uses NULL as placeholder for the missing values). In one part of the join one of the properties (a foreign key) is null whereas in the other one it contains a value (for the same unique ID). So my join will give me a result set like this:</p>
  
  <pre><code>ID     |    ForeignKey
  1           NULL
  1           123
  2           NULL
  3           NULL
  4           NULL
  4           234
  </code></pre>
  
  <p>I try to reduce this result set to contain only entries with a unique ID, but I cannot check the ForeignKey against NULL because then I would filter out all other rows where the key is NULL.</p>
  
  <p>What I am looking for is a way to tell SQL to check for the entire result set whether the same ID is used twice. If it finds such a duplicate (as the entries with ID 1 and 4 above) it should only display the one with the value (123 and 234). The entry with NULL should be filtered away.</p>
  
  <p>If no duplicate is found (as for ID 2 and 3) that entry should be used.</p>
  
  <p>So I want to transform the above result set to this:</p>
  
  <pre><code>ID     |    ForeignKey
  1           123
  2           NULL
  3           NULL
  4           234
  </code></pre>
  
  <p>I tried to solve the problem by using the OVER keyword and PARTITION By ID where I set the RowNumber to be equal to 1. This filters away the duplicate entries however it chooses always the entry with NULL instead of the one with the actual key, so the WRONG result looks like this:</p>
  
  <pre><code>ID     |    ForeignKey
  1           NULL
  2           NULL
  3           NULL
  4           NULL
  </code></pre>