问题
Simple one - what is the best way in Grails/Gorm to get the same effect as this SQL query:
SELECT YEAR(date) as SalesYear, MONTH(date) as SalesMonth, SUM(Price) AS TotalSales FROM Sales GROUP BY YEAR(date), MONTH(date) ORDER BY YEAR(date), MONTH(date)
回答1:
The executeQuery method of a domain class allows you to run HQL queries.
If you look at some examples, you will notice that the Hibernate Query Language remembers a lot SQL, but is object-oriented.
From the Grails docs:
The executeQuery method allows the execution of arbitrary HQL queries. HQL queries can return domain class instances, or Arrays of specified data when the query selects individual fields or calculated values.
So in your case, the query will return an array of the specified data, since don't matches with a Domain Class, but you will be able to iterate over this data.
Assuming that you mapped your sales table as Sales domain class:
class Sales {
Date date
BigDecimal price
...
static mapping = {
...
}
}
def result = Sales.executeQuery("SELECT YEAR(date) as SalesYear, MONTH(date) as SalesMonth, SUM(Price) AS TotalSales FROM Sales GROUP BY YEAR(date), MONTH(date) ORDER BY YEAR(date), MONTH(date)")
//iterate over the result
result.each { sales ->
println sales[0] //year
println sales[1] //month
println sales[2] //total
}
来源:https://stackoverflow.com/questions/13464500/gorm-equivalent-for-sql