【问题标题】:Using groupProperty and countDistinct in Grails Criteria在 Grails 标准中使用 groupProperty 和 countDistinct
【发布时间】:2010-09-15 17:15:33
【问题描述】:

我正在使用 Grails 1.2.4。我想知道如何按“countDistinct”(降序)和在预测中使用 groupProperty 进行排序。

这是我的域名:

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

在 MySQL 中,这就是我想要的:

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

一般来说,我想获得按产品交易次数(降序)排序的产品列表(或只是产品 ID)

这是我的猜测:

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

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

但这并没有给出我预期的结果。对此的任何线索将不胜感激。谢谢!

【问题讨论】:

    标签: grails criteria grails-orm


    【解决方案1】:

    试试这个:

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

    您的条件查询实际上相当于:

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

    注意区别。您想计算每个产品的不同交易数量,因此计算交易 ID(或任何交易属性)更有意义。产品 id 恰好在没有 distinct 子句的情况下工作。

    您可以打开超级有用的休眠 SQL 日志记录来调试此类问题。它将准确地向您展示您的标准是如何转换为 SQL 的。运行时:

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

    或将其放入您的 Config.groovy:

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

    编辑:使用countDistinct("id", "transactionCount") 作为投影,order("transactionCount") 将按计数排序。

    【讨论】:

    • 谢谢!有效。但是,您没有提到如何在 createCriteria 中按 'count(product_id) desc' 进行排序
    猜你喜欢
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2015-12-18
    • 1970-01-01
    相关资源
    最近更新 更多