gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:41:06 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com