Convert a static query to dynamic one, with a having clause
If I understand you right you just need to use the having() member function of the SelectQuery:

$query-&gt;having('count(po.oid) &gt; 0');


FYI you have this line twice:

$query-&gt;condition('pa.nid', $nid);


I don't think it'll make a difference to the query result but it's probably best to remove the duplicate line.