在GORM中按周/月/年分组 [英] Group by week / month / year in GORM

查看:212
本文介绍了在GORM中按周/月/年分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类费用{
日期dateOfExpense
int amount
}

我试图按星期/月分组/年的费用日期。
引用grails doc中的'sqlGroupProjection'方法 http://grails.org /doc/latest/guide/GORM.html



我尝试使用以下代码: - $ /

< (dateOfExpense,fromDate,toDate)
预测{
sqlGroupProjection'dateOfExpense,sum(amount)as summed pre $ def results = c { ',
'MONTH(dateOfExpense)',['date','summed'],[DATE,NUMBER]
}
}

抛出异常:

 没有这样的属性:DATE for类:grails.orm.HibernateCriteriaBuilder。 Stacktrace如下:
Message:没有这样的属性:DATE for class:grails.orm.HibernateCriteriaBuilder

请使用 sqlGroupProjection 方法建议一种方法

解决方案


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

  2. 为三个字段提供静态映射。

     静态映射= {
    //提供日期字段的确切列名称
    周公式('DATE_OF_EXPENSE')
    月份公式>


现在我们可以按照期望的字段进行分组

  def results = c.list {
之间(dateOfExpense,fromDate,toDate)
预测{
switch(groupBy){
caseweek:
groupProperty('year')
groupProperty('month')
groupProperty('week')
break;
casemonth
groupProperty('year')
groupProperty('month')
break;
caseyear:
groupProperty('year')
break;

sum('amount')
}
}


I have a domain class (minified) as :-

class Expense {
    Date dateOfExpense
    int amount
}

I am trying to get sum of amount grouped by week/month/ year of expense date. Referring to 'sqlGroupProjection' method in grails doc http://grails.org/doc/latest/guide/GORM.html,

I tried using following code:-

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

Throws exception:

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

Please suggest an approach using sqlGroupProjection method

解决方案

  1. Create three new numeric fields each for week,month and year in the domain class. These fields won't be mapped to column in the table.
  2. Provide static mapping for the three fields.

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

Now we can group by desired field using

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

这篇关于在GORM中按周/月/年分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆