Using groupProperty and countDistinct in Grails Criteria

前端 未结 1 1911
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 18:14

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:

相关标签:
1条回答
  • 2020-12-10 18:17

    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.

    0 讨论(0)
提交回复
热议问题