Skip to main content

Aggregate Function

The aggregate function in SwartzDB is used to perform calculations on a list of numeric values. It works seamlessly with the filter function when extracting numeric data.


How aggregate Works

The aggregate function supports several operations:

OperationDescription
SUMAdds up all values.
MINFinds the smallest value.
MAXFinds the largest value.
AVGComputes the average.
COUNTCounts the number of elements.

Example Usage:

$result = $sdb->aggregate([10, 20, 30], 'SUM');  
// Output: 60

Using aggregate with filter

Since filter extracts specific fields, it can return a list of numeric values. This list can then be passed directly into aggregate for calculations.

Example: Sum of All Prices

$filteredPrices = $sdb->filter($data, ["price"]);
$totalPrice = $sdb->aggregate($filteredPrices, 'SUM');
  • filter extracts only the "price" column.
  • aggregate calculates the total sum.

Example: Finding the Highest Score

$scores = $sdb->filter($data, ["score"]);
$maxScore = $sdb->aggregate($scores, 'MAX');
  • filter retrieves all scores.
  • aggregate finds the highest score.

Example: Calculating the Average Age

$ages = $sdb->filter($data, ["age"]);
$averageAge = $sdb->aggregate($ages, 'AVG');
  • filter extracts all ages.
  • aggregate computes the average.

Why Use aggregate with filter?

Dynamic calculations – Works with extracted data without needing manual processing.
Efficient – Processes only relevant values instead of looping through full datasets.
Readable Code – Makes operations like sum, min, and average easy to implement.


Conclusion

The combination of filter and aggregate provides a powerful way to process numerical data in SwartzDB. First, filter extracts a specific column, then aggregate performs calculations on the result.