Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to get only the first entry of a record if the record has multiple entries

Sourabh1
Tera Contributor

Hi All,

 

I am trying to get only the first entry of 'start' field for each 'id' value from 'metric_instance' table. Every incident has multiple entries in metric_instance table but I would like to get the value of the start and duration field when the incident appeared first in the list and the value of 'calculation complete' is true. I am able to sort the value of 'start' field but after that I am stuck. Request to kindly find the code till now below.

function run() {
var gr = new GlideRecord('metric_instance');
gr.addEncodedQuery('definition=39d43745c0a808ae0062603b77018b90^value=Analytics Settings Managers');
gr.orderBy('id');
gr.getUniqueValue('id');
//gr.setLimit(100);
//gr.setWorkflow(false);
//gr.autoSysFields(false);
gr.query();

var log = [];
while (gr.next()) {
log.push(gr.getDisplayValue('start'));

}
return log;
}
run();

 

Request to kindly help. I have attached an excel which shows the multiple entries.

 

 

 

2 REPLIES 2

jcmings
Mega Sage

You'll want to change from a while loop into an if statement. So instead of while (gr.next()), it'll be if (gr.next()). Also, it looks like you are sorting by 'id' right now; you'll want to change that to sort by the Start field. Make sure to add calculation_complete=true into your encoded query.

Sourabh1
Tera Contributor

I found the issue.

I was running the script in background script and I noticed something new. The command gr.orderBy('id'); does not execute on background script. When I ran the script in Fix script it ran perfectly.