grails - 在 Grails 标准中使用 groupProperty 和 countDistinct

标签 grails criteria grails-orm

我正在使用 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] }

但它没有给出我预期的结果。对此的任何领导都将受到高度赞赏。谢谢!

最佳答案

尝试这个:

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 恰好在没有不同条款的情况下工作。

您可以打开 super 有用的休眠 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")将按计数排序。

关于grails - 在 Grails 标准中使用 groupProperty 和 countDistinct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3720060/

相关文章:

Grails + MongoDB : what's a replacement for association query criteria?

hibernate - 使用 Grails Execector 插件的 runAsync ,为什么我需要事务来保存域对象?

grails - 在 IntelliJ 中运行 grails 测试时遇到困难 : Illegal use of nonvirtual function call

grails - 如何从生成的 Controller 中调用默认 Controller 的索引 Action ,或者如何从 Controller 中呈现索引 View ?

hibernate - 来自 Hibernate Criteria API 的 LIKE 限制

java - JPA:使用 criteriabuilder 查找实体:属性名称与注释不同?

hibernate - grails (GORM)/hibernate 中的多对多链接表

grails - Grails域类日期

grails - 重用域类的属性,约束和行为,而无需继承

java - Hibernate Criteria 来自单个查询的多个 rowCounts