Grails calculated field in SQL

北城以北 提交于 2019-12-11 02:28:02

问题


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 * quantity) 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.


回答1:


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]}"
}


来源:https://stackoverflow.com/questions/4855483/grails-calculated-field-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!