Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails group by date

I have a domain class with a date-property.

class Transaction {
    LocalDate time
    BigDecimal amount
}

How can I query for the sum of all transactions grouped by month? I can´t find any support for group by a date-range in GORM.

like image 943
Odinodin Avatar asked May 04 '12 20:05

Odinodin


1 Answers

Add a formula based field to your domain class for the truncated date:

class Transaction {
    LocalTime time
    BigDecimal amount
    String timeMonth

    static mapping = {
        timeMonth formula: "FORMATDATETIME(time, 'yyyy-MM')" // h2 sql
        //timeMonth formula: "DATE_FORMAT(time, '%Y-%m')"   // mysql sql
    }
}

Then you'll be able to run queries like this:

Transaction.withCriteria {
    projections {
        sum('amount')
        groupProperty('timeMonth')
    }
}
like image 164
ataylor Avatar answered Nov 15 '22 13:11

ataylor