How to use conditions on a COUNT Expression? I am creating an appointment booking module for my drupal 8 site, which is 99% complete, but I am one or two lines of code away from completing my module. The problem is using a database condition on an Count Expression that has been produced after the database has executed.

This is the code I have so far:

public static function dateavailabilty() {        
    $select = db_select('bookingdateandtime', 'e');
    $select-&gt;addField('e', 'datecode');
    $select-&gt;groupBy("e.datecode");
    $select-&gt;addExpression("COUNT(e.datecode)", 'count');
    $select-&gt;condition('count', 2, '&gt;');

    $entries = $select-&gt;execute()-&gt;fetchAll(\PDO::FETCH_ASSOC);

return $entries;}


But the page returns "The website encountered an unexpected error. Please try again later."

The following error report is produce in the Drupal Admin Error Log Messages:


  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Champ 'count' inconnu dans where clause: SELECT e.datecode AS datecode, COUNT(e.datecode) AS count FROM {bookingdateandtime} e WHERE (count > :db_condition_placeholder_0) GROUP BY e.datecode; Array ( [:db_condition_placeholder_0] => 2 ) in Drupal\booking\bookingDTdatabase::dateavail() (line 51 of C:\wamp\www\modules\booking\src\bookingDTdatabase.php).


I need to use a condition to only produce results that has a count of more than 2. Obviously, if I cancel out this line "$select->condition('count', 2, '>');", drupal returns everything perfectly. So, using the condition doesn't work on data that has been added after execution.

How do I go about using the correct condition to apply to the Expression?

Many Thanks for reading and helping.
Conditions on aggregates are addressed with HAVING in MySQL, so something similar to:

$select-&gt;having('count &gt; :cnt', [':cnt' =&gt; 2]);