views:

44

answers:

2

I'm at a loss of how to create a running sum of particular field after creating a criteria within a controller

I'm currently creating a set of set of records using:

    def b = Tapes.createCriteria()
    def yesterday =  b.list(sort: 'migratedDate', order: 'asc') {
        between ("migratedDate", dat.minus(1), dat)
    }

and counting the number of items in that set with

def num2 = Tapes.countByMigratedDateBetween(dat.minus(1), dat)

one of the fields in my domain is "migratedDuration", the system is returning the runtime of the process in milliseconds. Is there a way in the controller to create a sum of this number? Or should I have to do this via javascript in the corresponding .gsp file?

Thanks Again,

an awful awful hack

This worked perfectly, thanks

def todayTime = aa.list() { 
    between ("migratedDate", dat.minus(4), dat.minus(3)) 
    projections { sum('migratedDuration') 
    } 
}
+1  A: 

You can use a projection for this:

def b = Tapes.createCriteria()
def yesterday = b.list() {
    projections {
        sum('migratedDuration')
    }
}

A list of available Projections can be found here.

Rob Hruska
A: 

Is it truly a 'running sum' i.e. does it increment on each row or do you need the sum across all rows?

A sum across all rows can be done with a Projection (have a read of the doco for the "projections" closure provided by CriteriaBuider).

If it's a running total, you'll need to do that in the controller or view your self as you loop across the rows in the result list.

cheers

Lee

leebutts
Thanks! the following did the trick: def todayTime = aa.list() { between ("migratedDate", dat.minus(4), dat.minus(3)) projections { sum('migratedDuration') } }
awfulHack