Script to sort results list by state

mballinger
Mega Guru

Hello,

I have a background script that I need to be able to sort records by state. My state has several choices: Pending, Verified, Cancelled, Expired. The way this needs to be sorted is by most recently updated and pending state. All pending records should show first, but the states need to be grouped.

This is what I have so far:

var gr = new GlideRecord('u_custom_table');
gr.addQuery('active=true');
gr.groupBy('u_status');
gr.orderByDesc('u_status');
gr.orderByDesc('sys_updated');
gr.query();
while(gr.next()) {
   gs.print('u_number' + ' Updated on ' + gr.sys_updated + ' Status: ' + gr.u_status);
}

 Thanks!

 

1 ACCEPTED SOLUTION

Jake Sadler
Kilo Sage

Hi,

 

Simple fix for this. You need to use GlideAggregate for the groupBy method.

find_real_file.png

 

var agg = new GlideAggregate('incident');

agg.groupBy('state');

agg.orderByDesc('sys_updated');

agg.query();

View solution in original post

5 REPLIES 5

Hi,

 

There is only one way to do this and it has to be run  as a background script and involves the use of arrays.

 

var agg = new GlideAggregate('incident');

agg.addEncodedQuery('stateIsPeniding');

agg.orderByDesc('sys_updated');

agg.query();

var pending = [];

while(agg.next)){

pending.push(agg.sys_id);

}

 

var agg2 = new GlideAggregate('incident');

agg2.addEncodedQuery('stateIsNotPeniding');

agg2.groupBy('state');

agg2.orderByDesc('sys_updated');

agg2.query();

 

var other = [];

 while(agg2.next()){

 

other.push(agg2.sys_id);

}

 

var arr = new ArrayUtil();

var allStates = arr.concat(pending,other);

 

for (var i = 0; i < allStates.length; i++){

 

gs.print(allStates[i].toString());

}