Using db_select, how can I select all nodes with any of an array of taxonomy terms and order by the number of terms it is associated with? I have this so far:

// for example, $tags = array(2, 8, 18);
$query = db_select('node', 'n')
  -&gt;fields('n', array('nid'))
  -&gt;condition('n.type', 'post')
  -&gt;condition('n.status', 1);
$query-&gt;join('field_data_field_tags', 'tags', 'tags.entity_id = n.nid');
$query-&gt;condition('tags.field_tags_tid', $tags, 'IN');


I need to order these results by the number of "tags" associated with each node.

I've tried many things, using addExpression() with count() statements, then an orderBy(), etc, but I can't get it right.  Any help would be greatly appreciated!
You should put count as alias name in the count(*) and then groupby clause can be used on that column.

$query = db_select('node', 'n')
      -&gt;fields('n', array('nid'));
$query-&gt;addExpression('COUNT(n.nid)', 'count'); // addExpression
   $query-&gt;condition('n.type', 'post')
      -&gt;condition('n.status', 1);
    $query-&gt;join('field_data_field_tags', 'tags', 'tags.entity_id = n.nid');   
    $query-&gt;condition('tags.field_tags_tid', $tags, 'IN');
    $query-&gt;groupBy('count', 'DESC'); //count is column name given in the addExpression