Skip to main content
Version: v2.0

Aggregate records

Compute counts, sums, and other aggregates over a table's records without transferring the records themselves.

When to use this pattern

  • You need a count, sum, average, minimum, or maximum over matching records
  • You'd otherwise fetch pages of records just to count them
  • You need the records too — then use List and query records instead

Required values

ValueDescription
Table nameThe table to aggregate over (for example, incident)
AggregatesWhich of Count, SumFields, AvgFields, MinFields, MaxFields you want
Encoded queryOptional filter selecting the records that feed the aggregate

Example

package main

import (
"context"
"fmt"
"log"

servicenow "github.com/michaeldcanady/servicenow-sdk-go/v2"
aggregationapi "github.com/michaeldcanady/servicenow-sdk-go/v2/aggregationapi"
"github.com/michaeldcanady/servicenow-sdk-go/v2/credentials"
)

func main() {
// Step 1: Authenticate and initialize the client
cred := credentials.NewBasicProvider("{username}", "{password}")

client, err := servicenow.NewServiceNowServiceClient(
servicenow.WithAuthenticationProvider(cred),
servicenow.WithInstance("{instance}"),
)
if err != nil {
log.Fatalf("failed to initialize client: %v", err)
}

// Step 2: Choose the aggregates and the records they run over
wantCount := true
statsQuery := "active=true"
config := &aggregationapi.StatsRequestBuilderGetRequestConfiguration{
QueryParameters: &aggregationapi.StatsRequestBuilderGetQueryParameters{
Count: &wantCount,
SumFields: []string{"reassignment_count"},
Query: &statsQuery,
},
}

// Step 3: Request the aggregates — no records are transferred
response, err := client.Now().Stats("incident").Get(context.Background(), config)
if err != nil {
log.Fatalf("stats request failed: %v", err)
}

// Step 4: Read the aggregate values
result, err := response.GetResult()
if err != nil {
log.Fatal(err)
}
stats, err := result.GetStats()
if err != nil {
log.Fatal(err)
}
count, err := stats.GetCount()
if err != nil {
log.Fatal(err)
}

// Aggregate values come back as strings, as ServiceNow returns them
fmt.Printf("Active incidents: %s\n", *count)
}

Tips

  • Aggregate values come back as strings, exactly as ServiceNow returns them.
  • The module currently supports the ungrouped shape only — one aggregate result per request (sysparm_group_by isn't modeled yet).

Next steps

Was this page helpful?