Grails Gorm按天计算元素组,无需时间
我希望检索每天的用户配置文件注册列表。 域对象UserProfile存储日期creationDate属性。 我试过了Grails Gorm按天计算元素组,无需时间,grails,hql,gorm,grails-2.0,Grails,Hql,Gorm,Grails 2.0,我希望检索每天的用户配置文件注册列表。 域对象UserProfile存储日期creationDate属性。 我试过了 def results = UserProfile.executeQuery('select u.creationDate, count(u) from UserProfile as u group by u.creationDate') println results 这显然不是我所需要的,因为数据(已经)存储在其中,并且有完整的时间 任何资源精明的解决方案都适合:预测、hq
def results = UserProfile.executeQuery('select u.creationDate, count(u) from UserProfile as u group by u.creationDate')
println results
这显然不是我所需要的,因为数据(已经)存储在其中,并且有完整的时间
任何资源精明的解决方案都适合:预测、hql
Thnks将日期分解为
天
、月
和年
,然后忽略时间戳
这会给你你所需要的
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 ]
}
您可以将映射定义为公式,以提取日期和时间的日期部分。确切的公式将根据您使用的数据库而有所不同,对于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
分组,它应该可以执行您需要的操作
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 ]
}
或者,您可以使用另一个答案中建议的年、月和日的单独字段来代替“日期”,我认为这些函数在H2和MySQL中都是有效的。我使用HQL cast函数:
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
依赖于方言的原因,这是我不考虑这个选项的原因。你说得对。:)我在executequery:HibernateQueryException:中使用CAST()函数时遇到此异常,无法解析CAST:DATE的请求类型