Skip to main content
Book your demo
Example scripts
To homepage
Jira
Cloud icon
Cloud

Calculate the Sum of Fields from Multiple Work Items from a JQL Query

Created 1 year ago, Updated 0 day(s) ago
App in script
ScriptRunner For Jira
ScriptRunner For Jira
by Adaptavist
Compatibility
compatibility bullet
Jira
Language |
groovy
// sum up the values of this custom field
final customFieldName = 'Amount Paid'
final parentWorkItemKey = 'Parent Work Item Key'

def parentWorkItem = WorkItems.getByKey(parentWorkItemKey)
def subtasks = parentWorkItem.subtasks

// if the work item doesn't have any sub-tasks or is a subtask itself then no need for action
if (subtasks.empty) {
    return
}
def customFieldId = parentWorkItem.getNames().find { it.value == customFieldName }.key
if (!customFieldId) {
    logger.info "Custom field with name $customFieldName is not configured for work item type ${parentWorkItem.issueType.name} and space ${parentWorkItem.getSpaceObject().name}"
    return
}

def sum = subtasks.sum { subtask ->
    subtask.getCustomFieldValue(customFieldName) ?: 0
}

parentWorkItem.update {
    setCustomFieldValue(customFieldName, sum)
}
Having an issue with this script?
Report it here