Is it possible to use aggregate functions and properties in projections, criteria, Grails?

I use Grails Criteria (similar to hibernation criteria) to get a list of students who have received the highest marks in each unit from this table. And I want ONLY Name, Divisionand Grade.

Name | Division | Grade | Std_id
---------------------------------
AA1  | A        |  2     | 1
AA2  | A        |  4     | 2
BB1  | B        |  2     | 3
BB2  | B        |  5     | 4

As a result i want

Name | Division | Grade |
--------------------------
AA2  | A        |  4     |
BB2  | B        |  5     | 

if I use the following criteria

    def criteria = Student.createCriteria()
    def resultlt = criteria.list {
        projections {
            groupProperty('divison')
            max('grade')             
        }
    }

I received ONLY Divisionand Gradeother fields are not included. I need a box Name.

If I changed the criteria (used aggregate functions and property together in projections) to

    def criteria = Student.createCriteria()
    def resultlt = criteria.list {
        projections {
            property('name')
            groupProperty('divison')
            max('grade')

        }
    }

He gives the following error.

ERROR: column "this_.name" must appear in the GROUP BY clause or be
 used in an aggregate function
  Position: 63. Stacktrace follows:
org.postgresql.util.PSQLException: ERROR: column "this_.name" must
appear in the GROUP BY clause or be used in an aggregate function
  Position: 63
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryEx
ecutorImpl.java:2161)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutor
Impl.java:1890)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.ja
va:255)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Stat
ement.java:559)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(Abstract
Jdbc2Statement.java:417)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc
2Statement.java:302)
+4
source share
4 answers

. GROUP BY [*]. , " " , -. , .

+4

, createCriteria, - , :

def studentList = Student.executeQuery("from Student A where A.Grade in (select max(B.Grade) from Student as B group by B.Division)")
+1

. .

def studentDetails = Student.where {
grade == max(grade)}.property("name")).list().groupBy {"divison"}
+1

, @Gokul, name max:

    def resultlt = Student.withCriteria() {
        projections {
            max 'name'
            groupProperty 'divison'
            max 'grade'                  
        }
    }

.

0

Source: https://habr.com/ru/post/1654759/


All Articles