tags:

views:

623

answers:

3

How do I translate:

SELECT COUNT(*) AS `count`, `a` FROM `b` GROUP BY `a` ORDER BY `a`

into grails or gorm query?

A: 

I would try

def c = b.createCriteria()
def results = c {
   projections {
      groupProperty("a")
      rowCount()
   }
   order("a")
}

Note this is untested.

zentuit
This nearly solves the problem, but how do I order by count?
skurt
+4  A: 

Since grails 1.2 you can create aliases and order by the created alias.

See https://cvs.codehaus.org/browse/GRAILS-3875 and https://cvs.codehaus.org/browse/GRAILS-3655 for more details.

Applied to your own code, the HQL query would be :

def c = b.createCriteria() 
def results = c { 
  projections {
    groupProperty("a")
    count("a"), 'myCount' //Implicit alias is created here !
  }
  order 'myCount'
}
fabien7474
skurt
You are definitely right! See http://www.grails.org/1.3-RC2+Release+Notes and section and it seems that it is not implemented either in 1.3 (whereas the resolution issue is equal to fixed and Graeme is commenting that code was changed). So I think that you need to make a try :-) (Please keep us informed on the results)
fabien7474
A: 

working in grails 1.2.1

def c = C.createCriteria()
def pl = c.list {
    projections {
        countDistinct 'id', 'myCount'
        groupProperty 'a'
    }
    order ('myCount', 'desc')
}

the answer is for example

[[10,a3],[2,a1],[1,a2]]
skurt