6

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.

Odinodin
  • 2,147
  • 3
  • 25
  • 43
  • I don't know any GORM specific functions but if its ok for you - you could use database specific functions. I've used `GROUP BY MONTH(time)` for MySQL so far. – aiolos May 04 '12 at 21:46

1 Answers1

18

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')
    }
}
ataylor
  • 64,891
  • 24
  • 161
  • 189
  • 2
    Attention: When using CamelCase for domain properties you have to use underscore for the field name in sql syntax. e.g. datePhotoTaken will result in date_photo_taken – skurt Mar 19 '13 at 12:58
  • @timeMonth whether the property timeMonth will get mapped in db – Suganthan Madhavan Pillai Nov 28 '13 at 10:32
  • @Suganthan The property is not mapped in db but you have to add `timeMonth nullable: true` in constraints to avoid validation errors. – César Jan 30 '14 at 19:22
  • @César Thank you, but it is in domain class right, so whether timeMonth having a special reservation in grails – Suganthan Madhavan Pillai Jan 31 '14 at 03:28
  • @ataylor, I tried this code by I am getting exception: org.hibernate.QueryException: could not resolve property: week of: , I am using grails 2.3.x – sanghavi7 May 08 '14 at 08:53
  • @an5607ky, there is no property `week` in the example. Why not ask a new question including your code? – ataylor May 08 '14 at 14:07
  • I have asked question: http://stackoverflow.com/questions/23556773/how-to-set-formula-in-grails-domain-class – sanghavi7 May 09 '14 at 04:51