我正在使用Grails Criteria(类似于 hibernate 标准)来获取给定表中每个部门得分最高的学生的列表。我只想要 Name
、Division
和 Grade
字段。
Name | Division | Grade | Std_id
---------------------------------
AA1 | A | 2 | 1
AA2 | A | 4 | 2
BB1 | B | 2 | 3
BB2 | B | 5 | 4
我想要的结果是
Name | Division | Grade |
--------------------------
AA2 | A | 4 |
BB2 | B | 5 |
如果我使用以下标准
def criteria = Student.createCriteria()
def resultlt = criteria.list {
projections {
groupProperty('divison')
max('grade')
}
}
我只得到了Division
和Grade
,其他字段不包括在内。我还需要 Name
字段。
如果我将条件(在投影中一起使用聚合函数和属性)更改为
def criteria = Student.createCriteria()
def resultlt = criteria.list {
projections {
property('name')
groupProperty('divison')
max('grade')
}
}
它给出以下错误..
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)
最佳答案
这是一个常见的聚合问题。所选字段必须出现在 GROUP BY 子句[*] 中。正如我所看到的,您的部门列和名称列组合是无法比较的,因此您需要以另一种方式进行操作。我认为您需要针对上述条件进行子查询。
关于hibernate - 是否可以在 Projections、Criteria、Grails 中使用聚合函数和属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39523079/