Execute an aggregate function on the database.

@param  string  $function
@param  array   $columns
@return float|int
344342
public function aggregate($function, $columns = ['*'])
    {
        $this->aggregate = compact('function', 'columns');

        $previousColumns = $this->columns;

        if (!$this->from instanceof Subquery) {
            // We will also back up the select bindings since the select clause will be
            // removed when performing the aggregate function. Once the query is run
            // we will add the bindings back onto this query so they can get used.
            $previousSelectBindings = $this->bindings['select'];

            $this->bindings['select'] = [];
        }

        $results = $this->get($columns);

        // Once we have executed the query, we will reset the aggregate property so
        // that more select queries can be executed against the database without
        // the aggregate value getting in the way when the grammar builds it.
        $this->aggregate = null;

        $this->columns = $previousColumns;

        if (!$this->from instanceof Subquery) {
            $this->bindings['select'] = $previousSelectBindings;
        }

        if (isset($results[0])) {
            $result = array_change_key_case((array) $results[0]);

            return $result['aggregate'];
        }
    }
36823
public function select($columns = [])
    {
        $expr = new ColumnExpression($this->getSQLStatement());

        if ($columns instanceof Closure) {
            $columns($expr);
        } else {
            if (!is_array($columns)) {
                $columns = [$columns];
            }
            $expr->columns($columns);
        }
    }
908660
protected function runPaginationCountQuery($columns = ['*'])
    {
        if ($this->havings) {
            $query = $this->cloneWithout(['orders', 'limit', 'offset'])
                          ->cloneWithoutBindings(['order']);

            // We don't need simple columns, only specials
            // like subselects which is why we're using
            // havings after all.
            foreach ($query->columns as $key => $value) {
                if (is_string($value)) {
                    unset($query->columns[$key]);
                }
            }

            $countQuery = DB::table(DB::raw('('.$query->toSql().') as x'))->mergeBindings($query);

            // Using a aggregate here won't work when
            // groups are present because the
            // getCountForPagination() is
            // checking for it.
            if (!$this->groups) {
                $countQuery->setAggregate('count', $this->withoutSelectAliases($columns));
            }

            return $countQuery->get()->all();
        }

        return $this->cloneWithout(['columns', 'orders', 'limit', 'offset'])
                    ->cloneWithoutBindings(['select', 'order'])
                    ->setAggregate('count', $this->withoutSelectAliases($columns))
                    ->get()->all();
    }
1328982
public function min($column, bool $distinct = false): self
    {
        return $this->addFunction('aggregateFunction', 'MIN', $column, ['distinct' => $distinct]);
    }
451957
function setColumns($columns) {
		$this->columns = array();

		if ($columns === null) {
			return $this;
		}

		if (is_string($columns)) {
			return $this->addColumn($columns);
		}

		foreach ($columns as $alias => &$column) {
			$this->addColumn($column, is_int($alias) ? null : $alias);
		}
		return $this;
	}
629159
function using($columns)
    {
        $lastJoin = $this->getLastJoinSource();

        if (null === $columns) {
            $lastJoin->right = null;
            return $this;
        }

        $columns = is_array($columns) ? $columns : func_get_args();

        if ($lastJoin->right instanceof Using) {
            $lastJoin->right->expression = array_merge(
                $lastJoin->right->expression,
                $columns
            );
        } else {
            $lastJoin->right = new Grouping($columns);
        }
        return $this;
    }
900883
public function insert($columns) {
        // Check if array is associative
        if (Arr::is_assoc($columns)) {
            // Get array keys
            $arr_keys = array_keys($columns);

            // Get array values
            $arr_values = array_values($columns);

            $values = '';
            $fields = '';
            $insert  = [];

            // Build up the insert query
            $this->q->apd('INSERT INTO ' . $this->table_name . '(');

            for ($ii = 0; $ii < count($arr_keys); $ii++) {
                if ($ii != count($arr_keys) -1) {
                    $fields .= $arr_keys[$ii] . ', ';

                    if (!$this->is_SQL_function($arr_values[$ii])) {
                        $values .= ':' . $arr_keys[$ii] . ', ';
                        $insert[':' . $arr_keys[$ii]] = $arr_values[$ii];
                    } else {
                        $values .= $arr_values[$ii] . ', ';
                    }
                } else {
                    $fields .= $arr_keys[$ii] . ') VALUES (';

                    if (!$this->is_SQL_function($arr_values[$ii])) {
                        $values .= ':' . $arr_keys[$ii] . ')';
                        $insert[':' . $arr_keys[$ii]] = $arr_values[$ii];
                    } else {
                        $values .= $arr_values[$ii] . ')';
                    }
                }
            }

            // Finalize query
            $this->q->apd($fields . $values);

            try {
                $query = $this->db->prepare($this->q->get());
                $query->execute($insert);
                $this->clear();

                // Set last inserted id
                $this->lastInsertId = $this->db->lastInsertId();

                return true;
            } catch (\PDOException $e) {
                $this->setError('d', $e->getMessage());
                return false;
            }
        } else {
            echo 'Wrong array format';
            return false;
        }
    }
1279570
@SuppressWarnings({ "unchecked", "rawtypes" })
    public Table aggregate(ListMultimap<String, AggregateFunction<?,?>> functions) {
        Preconditions.checkArgument(!getSlices().isEmpty());
        Table groupTable = summaryTableName(sourceTable);
        StringColumn groupColumn = StringColumn.create("Group");
        groupTable.addColumns(groupColumn);
        for (Map.Entry<String, Collection<AggregateFunction<?,?>>> entry : functions.asMap().entrySet()) {
            String columnName = entry.getKey();
            int functionCount = 0;
            for (AggregateFunction function : entry.getValue()) {
                String colName = aggregateColumnName(columnName, function.functionName());
                ColumnType type = function.returnType();
                Column resultColumn = type.create(colName);
                for (TableSlice subTable : getSlices()) {
                    Object result = function.summarize(subTable.column(columnName));
                    if (functionCount == 0) {
                        groupColumn.append(subTable.name());
                    }
                    if (result instanceof Number) {
                        Number number = (Number) result;
                        resultColumn.append(number.doubleValue());
                    } else {
                        resultColumn.append(result);
                    }
                }
                groupTable.addColumns(resultColumn);
                functionCount++;
            }
        }
        return splitGroupingColumn(groupTable);
    }
669046
public function sum($column)  {
        $val = $this->_selectFunction(__FUNCTION__, $column)->scalar();
        return empty($val) ? 0 : $val;
    }
1183728
public function select($cols = array('*'))
    {
        if (!is_array($cols)) {
            $cols = func_get_args();
        }
        return new Query("SELECT", $cols, $this->connectionName);
    }
800696
private function update($columns, $values)
    {
        $query = Query::table(static::$table);
        //
        for ($i = 0; $i < Table::count($columns); $i++) {
            $query = !empty($values[$i]) ? $query->set($columns[$i], $values[$i]) : $query->set($columns[$i], 'null', false);
        }
        //
        $query->where($this->_keyName, '=', $this->_keyValue)
        ->update();
        //
        return $query;
    }
616190
final protected function getColumnSumWithAverages(array $columns, array $averages, array $constraints, $precision = 2)
    {
        $db = $this->db->select();

        foreach ($columns as $column) {
            $db->sum($column, $column);
        }

        foreach ($averages as $average) {
            $db->avg($average, $average);
        }

        $db->from(static::getTableName());

        if (!empty($constraints)) {
            // Iteration counter
            $iteration = 0;

            foreach ($constraints as $key => $value) {
                if ($iteration === 0) {
                    $db->whereEquals($key, $value);
                } else {
                    $db->andWhereEquals($key, $value);
                }

                $iteration++;
            }
        }

        $data = $db->queryAll();

        if (isset($data[0])) {
            return Math::roundCollection($data[0], $precision);
        } else {
            // No results
            return array();
        }
    }
50001
public static function make_assoc($columns, $array)
	{
		/* init the array */
		$assoc = array();

		/* set the cursor to */
		$cursor = 0;

		/* itterate over the data, and combine the data */
		foreach ($array as $record)
		{
			foreach ($record as $key => $value)
			{
				$assoc[$cursor][$columns[$key]] = $value;
			}
			$cursor++;
		}

		return $assoc;
	}
1178953
private function insert($columns, $values)
    {
        return Query::table(static::$table)
        ->column($columns)
        ->value($values)
        ->insert();
    }
161741
protected function getFresh($columns = [])
    {
        // If no columns have been specified for the select statement, we will set them
        // here to either the passed columns, or the standard default of retrieving
        // all of the columns on the table using the "wildcard" column character.
        if (is_null($this->columns)) {
            $this->columns = $columns;
        }

        // Drop all columns if * is present, MongoDB does not work this way.
        if (in_array('*', $this->columns)) {
            $this->columns = [];
        }

        // Compile wheres
        $wheres = $this->compileWheres();

        // Use MongoDB's aggregation framework when using grouping or aggregation functions.
        if ($this->groups || $this->aggregate) {
            return $this->getFreshGroupAndAggregate($wheres);
        }

        // Return distinct results directly
        if ($this->distinct) {
            return $this->getFreshDistinct($wheres);
        }

        return $this->getFreshNormal($wheres);
    }
765515
public function whereMultiple(array $columns)
    {
        $instance = $this->whereStrategyInstance();

        $instance->whereStrategy()->whereMultiple($columns);

        return $instance;
    }
456640
public function groupBy($array, $columns)
    {
        // ensure $columns parameter is array
        $columns = (array) $columns;

        // get first group-by column
        $col = array_shift($columns);

        $result = array();
        foreach ($array as $row) {
            $key = (string) is_object($row) ? $row->$col : $row[$col];
            if (!isset($result[$key])) {
                $result[$key] = array();
            }

            $result[$key][] = $row;
        }

        // do subsequent group by calls
        if (count($columns)) {
            foreach (array_keys($result) as $key) {
                $result[$key] = $this->groupBy($result[$key], $columns);
            }
        }

        return $result;
    }