Grails group by date

倖福魔咒の 提交于 2019-12-21 16:18:21

问题


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.


回答1:


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')
    }
}


来源:https://stackoverflow.com/questions/10455409/grails-group-by-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!