我有一个域名
class InvoiceLine {
String itemName
BigDecimal unitCost
Integer quantity
}
}
我想用.withCriteria做一个grails关闭,它会聚合(unitCost *数量),这样我最终得到了sql
select item_name, sum(unit_cost * quantity) from invoice_line group by item_name;
目前,我能想到的最好的是
def result = InvoiceLine.withCriteria {
projections {
groupProperty('itemName')
sum ('quantity * unitCost')
}
}
不幸的是,当我运行上面的代码时,grails会窒息。任何人都知道如何实现我的目标?任何帮助都非常感谢。
答案 0 :(得分:1)
是否需要成为条件查询? HQL在这里很有用:
def result = InvoiceLine.executeQuery(
"select itemName, sum(unitCost * quantity) " +
"from InvoiceLine " +
"group by itemName")
结果将是List
Object[]
,其中第一个元素是一个字符串(名称),第二个是数字(总和),所以例如你可以用类似的东西迭代
results.each { row ->
println "Total for ${row[0]} is ${row[1]}"
}