# Aggregate Functions

### Overview

The Aggregate Functions API allows you to perform statistical calculations (average, sum, minimum, maximum, count, list) on numeric fields in list responses. This enables data analysis and trend identification without making additional API calls.

### Endpoint

```
POST /ws/rest/{Resource}/aggregate
```

### Request Parameters

#### Query Parameters

Our standard filtering and expression functionality can be used to filter data before applying aggregate functions.

#### Request Body

The request body must contain a JSON object with a `functions` array that specifies which aggregate functions to perform on which fields.

```json
{
  "functions": [
    {
      "type": "string",  // Aggregate function type
      "field": "string"  // Field to aggregate
    }
  ]
}
```

**Supported Aggregate Function Types**

| Type  | Description                          | Applicable Fields   |
| ----- | ------------------------------------ | ------------------- |
| avg   | Calculates the average value         | Numeric fields only |
| sum   | Calculates the sum of all values     | Numeric fields only |
| min   | Finds the minimum value              | Numeric fields only |
| max   | Finds the maximum value              | Numeric fields only |
| count | Counts the number of non-null values | Any field           |
| list  | Returns a list of all unique values  | Any field           |

**Special Field Values**

* For `count` function, you can use `*` as the field value to count all records.

### Response

The API returns a JSON object with a `results` array containing the computed aggregate values.

```json
{
  "results": [
    {
      "type": "string",    // The aggregate function type
      "field": "string",   // The field that was aggregated
      "value": any         // The result of the aggregate function
    }
  ]
}
```

The `value` field will contain:

* A numeric value for `avg`, `sum`, `min`, `max`, and `count` functions
* An array of values for the `list` function

### Examples

#### Calculate Average of a Numeric Field

**Request:**

```
POST /ws/rest/VoyageHeader/aggregate
```

**Request Body:**

```json
{
  "functions": [
    {
      "type": "avg",
      "field": "doRobVoyageStart"
    }
  ]
}
```

**Response:**

```json
{
  "results": [
    {
      "type": "avg",
      "field": "doRobVoyageStart",
      "value": 125.4
    }
  ]
}
```

#### Calculate Multiple Aggregates with Filter or Expression

**Request:**

```
POST /ws/rest/VoyageHeader/aggregate?filter=voyage.isTc(EQ)true

POST /ws/rest/VoyageHeader/aggregate?expression=voyage.isTc=true
```

**Request Body:**

```json
{
  "functions": [
    {
      "type": "sum",
      "field": "foRobVoyageStart"
    },
    {
      "type": "min",
      "field": "foPriceVoyageStart"
    },
    {
      "type": "list",
      "field": "referenceNo"
    }
  ]
}
```

**Response:**

```json
{
  "results": [
    {
      "type": "sum",
      "field": "foRobVoyageStart",
      "value": 1250.6
    },
    {
      "type": "min",
      "field": "foPriceVoyageStart",
      "value": 450.75
    },
    {
      "type": "list",
      "field": "referenceNo",
      "value": ["V2023-001", "V2023-002", "V2023-003"]
    }
  ]
}
```

#### Count All Records

**Request:**

```
POST /ws/rest/VoyageHeader/aggregate
```

**Request Body:**

```json
{
  "functions": [
    {
      "type": "count",
      "field": "*"
    }
  ]
}
```

**Response:**

```json
{
  "results": [
    {
      "type": "count",
      "field": "*",
      "value": 123
    }
  ]
}
```

### Error Handling

The API validates the request and returns appropriate error messages:

* If an invalid function type is specified, the API returns HTTP 400.
* If an invalid field is specified, the API returns HTTP 400.
* If an incompatible function type is used with a field (e.g., "avg" on a text field), the API returns HTTP 400.

#### Error Response Example

```json
{
  "statusCode": 400,
  "message": "Cannot apply 'avg' function to field 'testText'. Only numeric fields are supported for this operation."
}
```

### Limitations

* Date aggregation functions (min/max) are not supported and will return a 400 error.
* Text fields cannot be used with numeric aggregate functions (avg, sum, min, max) and will return a 400 error.
* All fields must exist in the data model, or the request will be rejected.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://api.dataloy.com/api-release-8.25/user-guides/enterprise-functionality/aggregate-functions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
