How to get latest one incident record based on caller in servicenow

Haceena Shaik
Tera Expert

Hi Team,

 

I had a business requirement like, How to return list of latest  1 incident record based on caller.

Means, If Abel Tuter is having 8 incidents, I want the latest one incident.

 

Please help me with the approach.

 

Thanks in advance!

 

Regards,

Haseena

1 ACCEPTED SOLUTION

@Haceena Shaik ,

Please refer below code:

var incidentList = [];
var incident1 = new GlideRecord('incident');
incident1.query();
while(incident1.next()){
    var incident2 = new GlideRecord('incident');
   incident2.addQuery('caller_id',incident1.caller_id);
    incident2.orderByDesc('sys_created_on');
    incident2.query();
    if(incident2.next()){
        incidentList.push(incident2.number.toString());
    }
}
var uniqueIncidentList= new ArrayUtil().unique(incidentList);
gs.print(uniqueIncidentList);

Please let me know this code works for you or not

 

Please mark correct/helpful if this helps you!

View solution in original post

6 REPLIES 6

AshishKM
Kilo Patron
Kilo Patron

Hi @Haceena Shaik

I found you already accepted the solution but check the below code which is very much optimized.

This query is pushing all unique caller in an arrayLilst and then checking the latest incident for each caller. 

It's better to apply unique at first level for caller then take only latest incident using setLimit(1) along with orderByDesc(). 

 

var incidents = new GlideRecord('incident');
incidents.orderBy('caller_id.name');
incidents.query();
gs.info('---> ' + incidents.getRowCount());
var callerIdList = [];
while(incidents.next()) {
    
	callerIdList.push(incidents.caller_id.toString());
}
var arrayUtil = new ArrayUtil();
// remove all duplicate caller
callerIdList = arrayUtil.unique(callerIdList);
for (var i = 0; i < callerIdList.length; i++) {
    var incGr = new GlideRecord("incident");
		incGr.addQuery("caller_id",callerIdList[i]);
		incGr.orderByDesc("sys_created_on");
		// set limit because - we nedd only one latest record
		incGr.setLimit(1);  
		incGr.query();
		if(incGr.next()){
			gs.print("Caller="+incGr.caller_id.getDisplayValue()+" Latest Incident Number="+incGr.number);
		}
}

 

-Thanks,
AshishKM


Please mark this response as correct and helpful if it helps you can mark more that one reply as accepted solution

Servicenow34
Tera Guru

Hope below code helps.

var incident = new GlideRecord('incident');
incident.addQuery('caller_id=62826bf03710200044e0bfc8bcbe5df1');//Pass Caller id
incident.orderByDesc('sys_created_on');
incident.query();
if(incident.next()){
    gs.print(incident.number);
}

Kindly mark helpful/accepted if assists.

Thank you!