Using groupProperty and countDistinct in Grails Criteria

喜欢而已 提交于 2019-11-27 06:15:59

问题


I'm using Grails 1.2.4. I would like to know on how can I sort by "countDistinct" (descending) and with groupProperty inside a projections.

Here are my domains:

class Transaction {

    static belongsTo = [ customer : Customer, product : Product ]

    Date transactionDate = new Date()

    static constraints = {
        transactionDate(blank:false)    
    }

}

class Product {

    String productCode

    static constraints = {
        productCode(blank:false)    
    }
}

In MySQL terms, this is what I want:

select 
    product_id,
    count(product_id)
from
    transaction
group by
    product_id
order by
    count(product_id) desc

In general term, I would like to get a list of products (or just product id) sorted by the number of transactions a product had (descending)

This is my guess:

def c = Transaction.createCriteria() def transactions = c.list {
    projections {
        groupProperty("product")
        countDistinct("product")
    }
    maxResults(pageBlock)
    firstResult(pageIndex) }

def products = transactions.collect { it[0] }

But it doesn't give my expected result. Any lead on this will be highly appreciated. Thanks!


回答1:


Try this:

def c = Transaction.createCriteria() 
def transactions = c.list {
    projections {
        groupProperty("product")
        countDistinct("id")
    }
    maxResults(pageBlock)
    firstResult(pageIndex)
}

Your criteria query is actually equivalent to:

select 
    product_id,
    count(**distinct** product_id)
from
    transaction
group by
    product_id
order by
    count(product_id) desc

Note the distinct. You want to count the number of distinct transactions per product, so counting the transaction id (or any transaction property) makes more sense. Product id just happens to work without the distinct clause.

You can turn on the super useful hibernate SQL logging for debugging this kind of issue. It will show you exactly how your criterias are being transformed into SQL. At runtime:

org.apache.log4j.Logger.getLogger("org.hibernate").setLevel(org.apache.log4j.Level.DEBUG)

or throw this in your Config.groovy:

environments {
    development {
        log4j = {
            debug 'org.hibernate'
             }
     }
}

EDIT: use countDistinct("id", "transactionCount") as the projection and order("transactionCount") will sort by the count.



来源:https://stackoverflow.com/questions/3720060/using-groupproperty-and-countdistinct-in-grails-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!