在GORM中按周/月/年分组

时间:2012-12-29 15:51:39

标签: grails gorm

我有一个域类(缩小)为: -

class Expense {
    Date dateOfExpense
    int amount
}

我试图获得按周/月/费用日期分组的金额总和。 参考grails doc http://grails.org/doc/latest/guide/GORM.html中的'sqlGroupProjection'方法,

我尝试使用以下代码: -

def results = c {
    between("dateOfExpense", fromDate, toDate)              
    projections {
         sqlGroupProjection 'dateOfExpense,sum(amount) as summed',       
        'MONTH(dateOfExpense)',['date','summed'],[DATE,NUMBER]                  
    }
}

抛出异常:

 No such property: DATE for class: grails.orm.HibernateCriteriaBuilder. Stacktrace follows:
 Message: No such property: DATE for class: grails.orm.HibernateCriteriaBuilder

请使用sqlGroupProjection方法

建议一种方法

4 个答案:

答案 0 :(得分:5)

  1. 在域类中为每周,每月和每年创建三个新的数字字段。这些字段不会映射到表中的列。
  2. 为这三个字段提供静态映射。

    static mapping = {
         //provide the exact column name of the date field
         week formula('WEEK(DATE_OF_EXPENSE)')    
         month formula('MONTH(DATE_OF_EXPENSE)')
         year formula ('YEAR(DATE_OF_EXPENSE)')
    }
    
  3. 现在我们可以使用

    按所需字段进行分组
    def results = c.list {
      between("dateOfExpense", fromDate, toDate) 
      projections {
        switch(groupBy){
            case "week":
               groupProperty('year')
               groupProperty('month')
               groupProperty('week') 
            break;
            case "month"
               groupProperty('year')
               groupProperty('month')
            break;
            case "year":
               groupProperty('year')
            break;
        }        
        sum('amount')
      }
    }
    

答案 1 :(得分:1)

而不是这个

static mapping = {

week formula('WEEK(DATE_OF_EXPENSE)')    //provide the exact column name of the date field
month formula('MONTH(DATE_OF_EXPENSE)')
year formula ('YEAR(DATE_OF_EXPENSE)')

}

试试这个

static mapping = {

week formula: 'WEEK(DATE)'    
month formula: 'MONTH(DATE)'
year formula: 'YEAR(DATE)'

}

答案 2 :(得分:0)

尝试类似

的内容
sqlGroupProjection 'MONTH(dateOfExpense) as month, sum(amount) as summed',
    'month',['month','summed'],[NUMBER,NUMBER]

答案 3 :(得分:0)

sqlGroupProjection方法似乎支持不足。使用

def results = c.list {
    between("dateOfExpense", fromDate, toDate) 
    projections {
        groupProperty('dateOfExpense')
        sum('amount')
    }
}

将产生应得的结果。

如果您希望在截止日期前分组,请参阅Grails group by date(实际上,这完全超出了我的答案。但是我在长时间尝试您的代码后达到了相同的解决方案。)