开发者

Grails calculated field in SQL

I have a domain

class InvoiceLine {

String itemName
BigDecimal unitCost
Integer quantity
}

}

I would like to come up with a grails closure using .withCriteria that does an aggregation of the (unitCost * quant开发者_如何学City) so that I end up with sql

select item_name, sum(unit_cost * quantity) from invoice_line group by item_name;

For now, the best I could come up with is

def result = InvoiceLine.withCriteria {

        projections {
            groupProperty('itemName')
            sum ('quantity * unitCost')
        }
    }

Unfortunately, grails chokes up when I run the code above. Anyone have any idea how I could achieve my objective? Any help is highly appreciated.


Does it need to be a criteria query? HQL works great here:

def result = InvoiceLine.executeQuery(
  "select itemName, sum(unitCost * quantity) " + 
  "from InvoiceLine " +
  "group by itemName")

The results will be a List of Object[] where the 1st element is a String (the name) and the 2nd is a number (the sum), so for example you could iterate with something like

results.each { row ->
   println "Total for ${row[0]} is ${row[1]}"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜