title: group by not-null values
body: <p>I have a database:</p>
  
  <pre><code>+--+----+---------+
  |id|name|source_id|
  +--+----+---------+
  |11|aaaa|null
  +--+----+---------+
  |12|bbbb|1
  +--+----+---------+
  |13|cccc|1
  +--+----+---------+
  |14|dddd|null
  +--+----+---------+
  |15|eeee|2
  +--+----+---------+
  |16|ffff|2
  +--+----+---------+
  |17|gggg|2
  +--+----+---------+
  </code></pre>
  
  <p>I'd like to select all entries, with an exception:</p>
  
  <ul>
  <li>all entries with <code>source_id == somevalue(not null)</code> should be grouped</li>
  <li><strong>last entry</strong> with <code>source_id == null</code> should exist afterwards</li>
  </ul>
  
  <p>Here is the result I expect:</p>
  
  <pre><code>+----+--+----+---------+
  COUNT|id|name|source_id|
  +----+--+----+---------+
  .....|11|aaaa|null
  +----+--+----+---------+
  .2...|13|cccc|1
  +----+--+----+---------+
  .....|14|dddd|null
  +----+--+----+---------+
  .3...|17|ffff|2
  +----+--+----+---------+
  </code></pre>
  
  <p>So far I've done this (note: "change_count" = COUNT):</p>
  
  <pre><code>SELECT *, (To_days(date_expires)-TO_DAYS(NOW())) as dayDiff, COUNT(id) AS change_count FROM mytable
  GROUP BY source_id 
  HAVING dayDiff &lt; 4 
  ORDER BY date_created DESC
  </code></pre>
  
  <p>That's what I'm getting:</p>
  
  <pre><code>+----+--+----+---------+
  COUNT|id|name|source_id|
  +----+--+----+---------+
  .2...|11|aaaa|null
  +----+--+----+---------+
  .2...|12|bbbb|1
  +----+--+----+---------+
  .3...|15|eeee|2
  +----+--+----+---------+
  </code></pre>
  
  <p>As you can see the result has 2 problems:</p>
  
  <ul>
  <li>entries are grouped by first <code>source_id</code> occurrence (should be last(latest))</li>
  <li><code>nulls</code> are also grouped (shouldn't be grouped)</li>
  </ul>
  
  <p>Is the task that I've described above achievable? How do I do it?</p>
  
  <p>Edit:</p>
  
  <pre><code>SELECT *, COUNT(id) AS change_count FROM 
  (SELECT *, (To_days(date_return_due)-TO_DAYS(NOW())) as dayDiff FROM mytable 
  WHERE owner_id='1' 
  HAVING dayDiff &lt; 100 
  ORDER BY date_created DESC) AS newtable
  GROUP BY (CASE WHEN source_id IS NULL THEN id ELSE source_id END)
  ORDER BY (CASE WHEN source_id IS NULL THEN 1 ELSE 0 END), date_created DESC";
  </code></pre>