Usecase: Calculate the average resolution time for incidents by category.
Description: Develop a Script Include that calculates the average resolution time for incidents based on their category, providing insights into the performance of different incident categories.
Script Include
Working Code Answered question January 3, 2024
- Go to "System Definition" > "Script Includes" in ServiceNow.
- Click on "New" to create a new Script Include.
- Copy and paste the above code into the Script field.
- Save the Script Include.
Script Include to Calculate the average resolution time for incidents by category
// Name: IncidentResolutionTimeCalculator // Table: Incident var IncidentResolutionTimeCalculator = Class.create(); IncidentResolutionTimeCalculator.prototype = { initialize: function() { }, // Function to calculate average resolution time for a specific category calculateAverageResolutionTimeForCategory: function(category) { var gr = new GlideRecord('incident'); gr.addQuery('category', category); gr.addNotNullQuery('resolved_at'); gr.query(); var totalResolutionTime = 0; var incidentCount = 0; while (gr.next()) { var resolvedAt = new GlideDateTime(gr.resolved_at); var openedAt = new GlideDateTime(gr.opened_at); var resolutionTime = new GlideDuration(resolvedAt.getNumericValue() - openedAt.getNumericValue()); totalResolutionTime += resolutionTime.getNumericValue(); incidentCount++; } // Avoid division by zero if (incidentCount > 0) { var averageResolutionTime = totalResolutionTime / incidentCount; return new GlideDuration(averageResolutionTime).getDisplayValue(); } else { return "No resolved incidents in the specified category."; } }, type: 'IncidentResolutionTimeCalculator' };
you can use this Script Include in other scripts, such as Business Rules, UI Actions, or Scheduled Jobs, to calculate the average resolution time for incidents based on their category.
Example usage in a Business Rule:
// Business Rule to log average resolution time for Category A incidents var category = 'Category A'; // Set the desired category var calculator = new IncidentResolutionTimeCalculator(); var averageResolutionTime = calculator.calculateAverageResolutionTimeForCategory(category); gs.info("Average Resolution Time for " + category + ": " + averageResolutionTime);
Script Include
Working Code Edited answer January 3, 2024