繁体   English   中英

如何按最大日期和组同时获取grails中的记录

[英]How to fetch records in grails by max date and group at same time

我有一个看起来像这样的表:

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

期望的结果:

id    name   value    date_created
----  -----  ------   ---------
3     Red    <null>   10-24-2013
4     Orange light    10-24-2013

我可以用GORM做些什么来获得这个结果?

在纯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

我试过的:

    def c = Color.createCriteria()
    def results = c {
        projections {
            groupProperty("name")
            max("dateCreated")
        }
    }

但我无法弄清楚如何从投影中获取更多列? shade

如果您使用的是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"
    }
}

显式使用DetachedCriteria类有点难看,但它并不太糟糕。 此查询也应该可以作为Where查询,但似乎有一个错误,这意味着您不能将'=='与聚合函数一起使用。 修复错误后,您应该能够:

def colors = Color.where {
    dateCreated == max(dateCreated)
}.property("name").property("shade").property("dateCreated").list()

请注意,将'=='替换为'<'可以正常工作。

在HQL中,基本上你使用的是对象概念而不是表。 假设你有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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM