How to write a Drupal 7 query with "count" and "having" properties? I am unable to make the following query work in drupal7 standards..Can anyone help me with this? Its little urgent... 

SELECT n.nid AS nid, n.title AS title, count(n.title) AS ncount 
FROM node n 
INNER JOIN taxonomy_index tn ON n.nid = tn.nid 
WHERE (n.type = 'test') 
AND (tn.tid IN( 23,37)) 
AND (n.title LIKE '%name%') 
AND (n.status = 1) 
GROUP BY n.nid 
HAVING ncount = 2
This is off the top of my head so use caution...

$query = db_select('node', 'n')
  -&gt;fields('n', array('nid', 'title'))
  -&gt;condition('n.type', 'test')
  -&gt;condition('tn.tid', array(23, 37))
  -&gt;condition('n.title', '%' . db_like('name') . '%', 'LIKE')
  -&gt;condition('n.status', 1)
  -&gt;groupBy('n.nid');

// Add the COUNT expression
$query-&gt;addExpression('COUNT(n.title)', 'ncount');

// Add the HAVING condition
$query-&gt;havingCondition('ncount', 2);

// Add the JOIN
$query-&gt;join('taxonomy_index', 'tn', 'n.nid = tn.nid');

$results = $query-&gt;execute();