OBLYTECH Logo
OBLYTECH Logo

GlideAggregate in ServiceNow: Grouped Record Counts on the Server

GlideAggregate lets the database answer a summary question, such as how many incidents sit in each category, without loading records to count them in script. Add an aggregate with addAggregate, choose grouping fields with groupBy, run query, then read each group with getAggregate inside a next loop.

How a grouped count is built

A grouped count has the same five parts each time: create the object for a table, state what to calculate, state how to group, run the query, and walk the result rows. For the record-by-record counterpart, see GlideRecord explained.

var ga = new GlideAggregate('incident');
ga.addQuery('active', '=', 'true');
ga.addAggregate('COUNT');
ga.groupBy('category');
ga.query();
while (ga.next()) {
    gs.info(ga.getValue('category') + ': ' + ga.getAggregate('COUNT'));
}

The constructor takes the table name. addQuery adds a condition the same way it does on a record query, taking a field name, an operator and a value. addAggregate takes the type of calculation and, optionally, a field. The types you can pass are AVG, COUNT, GROUP_CONCAT, GROUP_CONCAT_DISTINCT, MAX, MIN, STDDEV and SUM.

Two details trip people up the first time. The first is that the loop does not hand you incident records. Each pass of next moves to a group, and the number for that group comes from getAggregate. The second is that getValue reads the grouping field for the current group, so the category you print belongs to the row you are standing on.

COUNT is the natural choice when the question is how many. The other types take a field, because averaging or summing needs something to work on. A call such as addAggregate('AVG', 'sys_mod_count') is paired with getAggregate('AVG', 'sys_mod_count') when you read it back. The pairing matters: the arguments you used to add the aggregate are the arguments you use to read it.

Grouping by more than one field

groupBy can be called more than once, which gives you one row per combination of the fields you named. Counting incidents by category and by state is two calls:

var ga = new GlideAggregate('incident');
ga.addAggregate('COUNT');
ga.groupBy('category');
ga.groupBy('state');
ga.query();
while (ga.next()) {
    gs.info(ga.getValue('category') + ' / ' + ga.getValue('state') +
        ' = ' + ga.getAggregate('COUNT'));
}

Because each combination is its own row, a second grouping field increases the number of rows you loop over. For wider guidance on query cost, see slow queries and GlideRecord performance and platform performance.

orderBy also groups

The ordering methods have a side effect that is easy to miss. The field you order by in orderBy and orderByDesc is added to the group-by list. So this loop groups by category even though no groupBy call appears:

var ga = new GlideAggregate('incident');
ga.addAggregate('COUNT');
ga.orderBy('category');
ga.query();

If you call groupBy on one field and orderBy on another, the query is grouped by both. When a count looks too fragmented, look for an orderBy call that added a grouping field you did not intend. In a scoped application, the method getEncodedQuery returns the encoded query for the object, and after grouping by category its output takes the form ORDERBYcategory^GROUPBYcategory, which makes the added grouping visible.

The orderBy parameter can also be a glidefunction, such as one that works on the length of a field, which orders by a computed value rather than a stored one.

Ranking groups by their count

Ordering by a field gives you alphabetical or numeric order of the group labels. A report such as the busiest categories needs the groups ordered by the number inside them. That is what orderByAggregate is for. It takes the aggregate type and the field:

var ga = new GlideAggregate('incident');
ga.addAggregate('COUNT', 'category');
ga.groupBy('category');
ga.orderByAggregate('COUNT', 'category');
ga.query();
while (ga.next()) {
    gs.info(ga.getValue('category') + ' ' + ga.getAggregate('COUNT', 'category'));
}

orderByAggregate orders results by the specified aggregate on the specified field. Pair it with the same type and field you passed to addAggregate, so the ranking and the number you print refer to the same calculation.

Keeping only the groups that matter

Filtering with addQuery removes records before they are counted. Sometimes the question is about the groups themselves, such as which categories have more than a certain number of incidents. That is a different job, and the global GlideAggregate API has addHaving for it. It filters aggregate results in the way a SQL HAVING clause does. The three-argument form takes the aggregate, an operator and a value, and a four-argument form adds a field name so the filter applies to a specific field.

var ga = new GlideAggregate('incident');
ga.addAggregate('COUNT');
ga.groupBy('category');
ga.addHaving('COUNT', '>', '5');
ga.query();
while (ga.next()) {
    gs.info(ga.getValue('category') + ' ' + ga.getAggregate('COUNT'));
}

The distinction between the two filters is worth keeping straight, because the same sentence can be written either way and mean different things:

Question Tool What it filters
Count only active incidents addQuery or addEncodedQuery Records, before grouping
Show only categories with more than five incidents addHaving Groups, after counting
Show only records where a field is empty or filled addNullQuery or addNotNullQuery Records, before grouping

addEncodedQuery takes a standard encoded query string such as active=true and adds it to whatever conditions already exist, which is useful when the condition was copied from a list filter. addNullQuery and addNotNullQuery take a field name and add a condition that the field is empty or not empty. For how these strings are written, see the encoded query explainer.

Limiting the table rows an aggregate reads

A ranked list rarely needs to show all groups, but setAggregateWindow does not rank groups. It limits the table rows included in the aggregate query. It takes a first row and a last row, both zero-based, where the first is inclusive and the last is exclusive. A call of setAggregateWindow(0, 10) keeps the first ten rows.

var ga = new GlideAggregate('incident');
ga.addAggregate('COUNT', 'category');
ga.groupBy('category');
ga.orderByAggregate('COUNT', 'category');
ga.setAggregateWindow(0, 10);
ga.query();

The exclusive end is an easy slip. If you want rows zero through nine, the second argument is ten. Set the window before calling query.

Counting over time with addTrend

When the grouping field is a date, addTrend groups results over time. It takes the field, a time interval and an optional number of units. The intervals are date, dayofweek, hour, minute, quarter, value, week and year. The units argument applies to the minute interval and defaults to one.

var ga = new GlideAggregate('incident');
ga.addAggregate('COUNT');
ga.addTrend('opened_at', 'quarter');
ga.query();

For day-of-week trends there is a related setting, setIntervalYearIncluded. By default the year is included, so Mondays from different years form separate groups. Passing false removes the year, which gives a single Monday group across years. It requires addTrend with the dayofweek interval. The global API also lists addBizCalendarTrend, which groups records into business calendar time spans using the sys_id of a calendar.

Reading group totals, row counts and group queries

A few methods help once the loop is running.

getRowCount returns the number of rows in the GlideAggregate object. In a grouped query each row is a group, so do not confuse it with the count inside a group.

getTotal, listed in the global API, returns a number by summing an aggregate. It takes the aggregate and the name of the field to aggregate.

getAggregateEncodedQuery returns the encoded query that selects the current group, in a form such as category=database. This is the useful one when a summary has to link to the records behind a number. Build a GlideRecord on the same table and pass that string to addEncodedQuery to get the records in that group. Add any filters you set on the aggregate as well, so the detail list matches the count. For counts shown in charts rather than scripts, see reporting and dashboards.

var ga = new GlideAggregate('incident');
ga.addAggregate('COUNT');
ga.groupBy('category');
ga.query();
while (ga.next()) {
    var detail = new GlideRecord('incident');
    detail.addEncodedQuery(ga.getAggregateEncodedQuery());
    detail.setLimit(5);
    detail.query();
    // work with the sample records for this group
}

Currency fields and mixed values

When getAggregate runs over a currency field, the value comes back as a string in the form currency code, semicolon, currency value. If the values in the group use different currencies, the return is a lone semicolon. Code that sums currency and then does arithmetic on the result needs a branch for that mixed case.

Scoped and global applications

GlideAggregate has both a scoped and a global reference page. The scoped page covers addAggregate, addQuery, addEncodedQuery, the null checks, addTrend, groupBy, orderBy, orderByDesc, orderByAggregate, setAggregateWindow, setGroup, getEncodedQuery and the getters. The global page adds addHaving, getTotal, getQuery and addBizCalendarTrend, which the scoped page does not list. If the script lives in a scoped application, check the method against the scoped page before building a feature around it.

Two settings that appear on both pages are worth knowing about. setAggregateWorkflow turns business rule execution on or off for aggregate queries, with a default of false, and the session workflow setting overrides it. setCategory sets the query category, which determines how the query is routed to a secondary database. On the scoped page the category refers to the Secondary Database Categories table, and the method requires the Secondary Database Pools plugin. For background on the rules this setting affects, see business rules explained.

Frequently asked questions

How do I count records per category with GlideAggregate?

Create the object for the table, call addAggregate with COUNT, call groupBy on the category field, run query, and read each group's number with getAggregate inside a next loop.

Can I group by two fields?

Yes. groupBy can be called more than once, and you get one row for each combination of the fields.

Why is my count grouped by a field I did not name?

orderBy and orderByDesc add their field to the group-by list. Log getEncodedQuery to see which fields ended up in the grouping.

How do I list only the groups above a certain count?

Use addHaving in the global API. It filters on the aggregate result, while addQuery filters records before they are counted.

Does setAggregateWindow return only the top groups?

No. It limits the table rows included in the aggregate query, not the groups, so it does not pick groups by rank. To rank groups by count, use orderByAggregate.

How do I get from a group back to its records?

getAggregateEncodedQuery returns the encoded query for the current group. Pass it to addEncodedQuery on a record query for the same table.