简单的一个 - 在 Grails/Gorm 中获得与此 SQL 查询相同效果的最佳方法是什么:
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)
简单的一个 - 在 Grails/Gorm 中获得与此 SQL 查询相同效果的最佳方法是什么:
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)
域类的executeQuery方法允许您运行HQL查询。
如果您查看一些示例,您会注意到Hibernate 查询语言会记住很多 SQL,但它是面向对象的。
来自 Grails 文档:
executeQuery 方法允许执行任意 HQL 查询。当查询选择单个字段或计算值时,HQL 查询可以返回域类实例或指定数据的数组。
因此,在您的情况下,查询将返回指定数据的数组,因为不匹配域类,但您将能够迭代此数据。
假设您将销售表映射为销售域类:
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
}