How to get records in grails by maximum date and group at the 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?

In pure sql, this is a query that gives me the desired result:

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 tried:

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

But I can not figure out how to get more columns from the projection? i.e. columnshade

+5
source share
2 answers

You can do this with individual criteria if you are using Grails 2.0 or higher:

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()

, '==' '<' .

+8

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)
-3

All Articles