この場合に私がやりたいのは、sum() と group by 句を使用して単純な sql で行うのと同じように、クエリ自体で結果をグループ化して合計することです。Grails は Hibernate に基づいており、これらのケースに最適なselect new map()構文としての Hibernate です。
以下は、Grails で月ごとの財務合計を選択する例です (金融取引など)。
def query = """
select new map(sum(tx.value) as total, month(tx.date) as month, year(tx.date) as year)
from Transaction tx
where tx.date >= :beginDate and tx.date < :endDate
group by month(tx.date), year(tx.date)
order by year(tx.date) desc , month(tx.date) desc
"""
def result = Transaction.executeQuery(query,[beginDate:someDate, endDate:anotherDate])
result
そのコードを使用すると、変数をループして、マップである各結果アイテムを取得できます。そのようです:
result.each{ item ->
println "Financial total for ${item.month}/${item.year} is equal to ${item.total}"
}
これは非常にシンプルで、ポイントソリューションに直結していると思います。よろしく...