【问题标题】:Gorm count elements group by day without timeGorm count 元素按天分组,没有时间
【发布时间】:2014-02-11 22:38:15
【问题描述】:

我希望检索每 的 UserProfile 注册列表。 域对象 UserProfile 存储一个 Date creationDate 属性。 我试过了

def results = UserProfile.executeQuery('select u.creationDate, count(u) from UserProfile as u group by u.creationDate')
println results

这显然不是我需要的,因为数据(已经)完整地存储在其中。

任何精通资源的解决方案都适合:投影、hql、...

谢谢

【问题讨论】:

    标签: grails hql grails-orm grails-2.0


    【解决方案1】:

    我使用 HQL 转换函数:

    def results = UserProfile.executeQuery("""
      select cast(u.creationDate as date), count(u) 
      from UserProfile as u 
      group by cast(u.creationDate as date)
    """)
    

    底层数据库必须支持 ANSI cast(... as ...) 语法才能工作,PostgreSQL、MySQL、Oracle、SQL Server 和许多其他 DBMS 就是这种情况

    【讨论】:

    • 我在执行查询中使用 CAST() 函数时遇到此异常:HibernateQueryException:无法解析 CAST 的请求类型:DATE
    【解决方案2】:

    将日期分解为daymonthyear,然后忽略timestamp

    这应该可以满足您的需求。

    def query = 
    """
    select new map(day(u.creationDate) as day, 
                   month(u.creationDate) as month, 
                   year(u.creationDate) as year, 
                   count(u) as count)
           from UserProfile as u
           group by day(u.creationDate), 
                    month(u.creationDate), 
                    year(u.creationDate)
    """
    
    //If you do not worry about dates any more then this should be enough
    def results = UserProfile.executeQuery( query )
    
    //Or create date string which can be parsed later
    def refinedresults = 
        results.collect { [ "$it.year-$it.month-$it.day" : it.count ] }
    
    //Or parse it right here
    def refinedresults = 
        results.collect {
            [ Date.parse( 'yyyy-MM-dd', "$it.year-$it.month-$it.day" ) : it.count ]
        }
    

    【讨论】:

      【解决方案3】:

      您可以定义一个映射为公式的"derived" property,以提取日期和时间的日期部分。确切的公式会因您使用的数据库而异,对于 MySQL,您可以使用类似

      Date creationDay // not sure exactly what type this needs to be, it may need
                       // to be java.sql.Date instead of java.util.Date
      
      static mapping = {
        creationDay formula: 'DATE(creation_date)'
      }
      

      (公式使用 DB 列名而不是 GORM 属性名)。现在您可以按creationDay 而不是creationDate 分组,它应该可以满足您的需要。

      或者,您可以按照其他答案中的建议使用单独的年、月和日字段来代替“日期”,我认为这些函数在 H2 和 MySQL 中都有效。

      【讨论】:

      • 对方言的依赖是我不考虑这个选项的原因。你是对的。 :)
      猜你喜欢
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2015-02-12
      • 1970-01-01
      相关资源
      最近更新 更多