[英]How to fetch records in grails by max date and group at same time
I have a table that looks like this: 我有一个看起来像这样的表:
id name shade date_created
---- ----- ------- ---------------
1 Red bright 10-28-2012
2 Orange light 10-28-2012
3 Red <null> 10-24-2013
4 Orange light 10-24-2013
Desired Result: 期望的结果:
id name value date_created
---- ----- ------ ---------
3 Red <null> 10-24-2013
4 Orange light 10-24-2013
What can I do with GORM to get this result? 我可以用GORM做些什么来获得这个结果?
In pure sql this is the query that gets me the desired result: 在纯sql中,这是获得所需结果的查询:
SELECT t.name, t.shade, r.MaxTime
FROM (SELECT name, MAX(date_created) as MaxTime
FROM colorable
GROUP BY name) r
INNER JOIN colortable t ON t.name = r.name AND t.date_created = r.MaxTime
What I've Tried: 我试过的:
def c = Color.createCriteria()
def results = c {
projections {
groupProperty("name")
max("dateCreated")
}
}
But I can't figure out how to fetch more columns from the projection? 但我无法弄清楚如何从投影中获取更多列? ie the shade
column 即shade
柱
You can do this with detached criteria if you're using Grails 2.0 or above: 如果您使用的是Grails 2.0或更高版本,则可以使用分离标准执行此操作:
def colors = Color.withCriteria {
eq "dateCreated", new grails.gorm.DetachedCriteria(Color).build {
projections {
min "dateCreated"
}
}
projections {
property "name"
property "shade"
property "dateCreated"
}
}
The explicit use of the DetachedCriteria
class is a bit ugly, but it's not too bad. 显式使用DetachedCriteria
类有点难看,但它并不太糟糕。 This query should also be doable as a Where query, but there appears to be a bug which means you can't use '==' with aggregate functions. 此查询也应该可以作为Where查询,但似乎有一个错误,这意味着您不能将'=='与聚合函数一起使用。 Once the bug is fixed, you should be able to do: 修复错误后,您应该能够:
def colors = Color.where {
dateCreated == max(dateCreated)
}.property("name").property("shade").property("dateCreated").list()
Note that replacing '==' with '<' works fine. 请注意,将'=='替换为'<'可以正常工作。
In HQL, basically you use a object notion instead of table. 在HQL中,基本上你使用的是对象概念而不是表。 So assuming that you have the Color domain class: 假设你有Color域类:
String hql = " select c from ( select name,"
hql += " max(dateCreated) as maxTime "
hql += " from Color "
hql += " group by name ) as t"
hql += " inner join Color c on c.name = t.name and c.dateCreated = t.maxTime "
def result = Color.executeQuery(hql)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.