protected function aggregate($function, $column = null)
    {
        if ($column === null) {
            if ($this->hasExactlyOneColumn()) {
                if (($pos = strpos($this->columns[0], ' AS ')) !== false) {
                    $column = substr($this->columns[0], 0, $pos);
                }
                else {
                    $column = $this->columns[0];
                }
                $bindings = $this->bindings['select'];
            }
            else {
                $column   = '*';
                $bindings = [];
            }
        }
        else {
            $column   = $this->db->quoteName($column);
            $bindings = [];
        }

        $flags = !empty($this->flags) ? implode(' ', $this->flags) . ' ' : '';

        $query = 'SELECT ' . $function . '(' . $flags . $column . ')'
            . $this->buildFrom()
            . $this->buildJoin()
            . $this->buildWhere();

        foreach (['from', 'join', 'where'] as $clause) {
            if (!empty($this->bindings[$clause])) {
                $bindings = array_merge($bindings, $this->bindings[$clause]);
            }
        }

        $result = $this->db->scalar($query, $bindings);

        return $result ?: 0;
    }