kitees
kitees

Reputation: 11

Accumulate Field Values using Groovy

I have the follwing columns KPI_PERIOD and KPI_VALUE and want to achieve a new column named KPI_Output using Groovy.

The logic to achieve the KPI_Output is adding up the values of KPI_Value. In other words, for Apr the KPI_Output is the same as KPI_Value, as it's the first month. For May the KPI_Output value is KPI_Values of Apr and May. For Jun the KPI_Output is KPI_Values of Apr, May, and June. For Jul the KPI_Output value is KPI_Value of Apr, May, Jun, and Jul - and so on....

KPI_PERIOD  KPI_VALUE   KPI_Output 
Apr         33091       33091 
May         29685       62776
Jun         31042       93818
Jul         32807       126625
Aug         32782       159407
Sep         34952       194359
Oct         32448       226807
Nov         31515       258322
Dec         24639       282961
Jan         25155       308116
Feb         31320       339436
Mar         33091       372527

How can I achieve this using Groovy?

Desired Results

Upvotes: 0

Views: 536

Answers (1)

Opal
Opal

Reputation: 84756

Here You go:

def input = """KPI_PERIOD  KPI_VALUE
Apr 33091    
May 29685   
Jun 31042   
Jul 32807   
Aug 32782   
Sep 34952   
Oct 32448   
Nov 31515   
Dec 24639   
Jan 25155   
Feb 31320   
Mar 33091   
"""

def splitted = input.split('\n')[1..-1]
sum = 0
def transformed = splitted.collect { it.split(/\s+/)*.trim() }.inject([]) { res, curr ->
    sum += curr[1].toInteger()
    curr << sum.toString()
    res << curr    
}
println "KPI_PERIOD    KPI_VALUE   KPI_OUTPUT"
transformed.each { 
    println "${it[0].padLeft(10)} ${it[1].padLeft(12)} ${it[2].padLeft(12)}"
}

Hope it's all clear, if not feel free to ask.

Upvotes: 1

Related Questions