I have a grails domain like this
Point {
User user
Date assignedDate = new Date()
consumed = false
}
I want to do a query that return rows with user, count(consumed=true), count(consumed=false)
for example with data
| USER | DATE | CONSUMED |
___________________________
| 1 | ... | true |
| 1 | ... | true |
| 1 | ... | false |
| 2 | ... | true |
| 2 | ... | false |
the query must return:
| USER | CONSUMED | NOT CONSUMED |
_________________________________
| 1 | 2 | 1 |
| 2 | 1 | 1 |
I have to do this in a single query because I need pagination. Best if done with gorm criteria or hibernate HQL.
I have tried playing with projections but without success.
Any idea? Thank you
Workaround
As a workaround I have used hibernate formula mapping with formula suggested by Michael J. Lee.
I have added two mapped fields to
Point { User user Date assignedDate = new Date() consumed = false free formula: "CASE WHEN consumed = 0 THEN 1 ELSE 0 END" notFree formula: "CASE WHEN consumed = 1 THEN 1 ELSE 0 END" }
And user a criteria query like:
Point.withCriteria{ projections { groupProperty('user') sum('free') sum('notFree') } }