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.

JavaScript Grouped Order By

Daniel Banks
Tera Contributor

Hi All,

 

I am new to ServiceNow and completely new to JavaScript. I have been trying to work on running a JavaScript query adapting what I have found elsewhere which works fine. However, I am wanting to now add a sort by or sort by descending order for the grouped count. 

 

I have seen on previous posts something along the lines of below:

 

var gr = new GlideRecord('alm_asset');
gr.orderBy('display_name'); // Ascending Order
//gr.addEncodedQuery(queryString);
gr.query();
while (gr.next()) {
gr.orderByDesc()
gs.info(gr.number+" P:"+gr.display_name);
}

 

 

However, I'm having trouble adapting this into my current script and get it to work: -

 

getDuplicateAssetforAssignedTo: function() {
var str = [];
var gr = new GlideAggregate('cmdb_ci');
gr.addAggregate('COUNT', 'serial_Number');
gr.groupBy('serial_Number');
gr.addHaving('COUNT', '>', 1);
gr.query();
while (gr.next()) {
str.push(gr.getValue('serial_Number') + '');
}
return str.toString();

},
});

 

Any help will be much appreciated and thank you in advance for your help on the above.

8 REPLIES 8

Yousaf
Giga Sage

Hi Daniel,

Please see if this can help.

How to get the Top 10 values from a table using the GlideAggregate function 

 

Mark Correct and Helpful if it helps.


***Mark Correct or Helpful if it helps.***

suvro
Mega Sage

try this

getDuplicateAssetforAssignedTo: function() {
var str = [];
var gr = new GlideAggregate('cmdb_ci');
//gr.addAggregate('COUNT', 'serial_Number');
gr.groupBy('serial_Number');
gr.addHaving('COUNT', '>', 1);
gr.query();
while (gr.next()) {
str.push(gr.getValue('serial_Number') + '');
}
return str.toString();

},


 

Thank you for your reply, I've tried removing that line and still no luck. 

SanjivMeher
Mega Patron
Mega Patron

I think you can just use gr.orderByAggregate('COUNT'); to achieve it.

 

getDuplicateAssetforAssignedTo: function() {
var str = [];
var gr = new GlideAggregate('cmdb_ci');
gr.addAggregate('COUNT', 'serial_Number');
gr.groupBy('serial_Number');
gr.addHaving('COUNT', '>', 1);

gr.orderByAggregate('COUNT');
gr.query();
while (gr.next()) {
str.push(gr.getValue('serial_Number') + '');
}
return str.toString();

},
});

 

Reference

https://developer.servicenow.com/dev.do#!/reference/api/quebec/server_legacy/no-namespace/c_GlideAgg...


Please mark this response as correct or helpful if it assisted you with your question.