1

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

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

4 回答 4

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

现在我们可以使用所需的字段进行分组

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')
  }
}
于 2013-01-02T09:28:35.907 回答
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)'

}
于 2014-08-27T14:00:10.640 回答
0

尝试类似的东西

sqlGroupProjection 'MONTH(dateOfExpense) as month, sum(amount) as summed',
    'month',['month','summed'],[NUMBER,NUMBER]
于 2012-12-29T16:00:12.340 回答
0

这种sqlGroupProjection方法似乎没有得到很好的支持。采用

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

会产生应有的结果。

如果您想按日期分组,请参阅按日期分组的 Grails(实际上,它完全超过了我的答案。但是在尝试了您的代码很长时间后,我得到了相同的解决方案。)

于 2012-12-29T16:45:03.950 回答