我正在使用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] }
但它没有给出我预期的结果。任何领导都将受到高度赞赏。谢谢!
答案 0 :(得分:8)
试试这个:
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子句的情况下工作。
您可以打开超级有用的hibernate 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")
将按计数排序。