一个返回聚集值(aggregate values)的查询可以按照一个返回的类或组件(components)中的任何属性(property)进行分组:
select cat.color, sum(cat.weight), count(cat) from Cat cat group by cat.color
select foo.id, avg(name), max(name) from Foo foo join foo.names name group by foo.id
having
子句在这里也允许使用.
select cat.color, sum(cat.weight), count(cat) from Cat cat group by cat.color having cat.color in (eg.Color.TABBY, eg.Color.BLACK)
如果底层的数据库支持的话(例如不能在MySQL中使用),SQL的一般函数与聚集函数也可以出现
在having
与order by
子句中。
select cat from Cat cat join cat.kittens kitten group by cat.id, cat.name, cat.other, cat.properties having avg(kitten.weight) > 100 order by count(kitten) asc, sum(kitten.weight) desc
注意group by
子句与
order by
子句中都不能包含算术表达式(arithmetic expressions).
也要注意Hibernate目前不会扩展group的实体,因此你不能写group by cat
,除非cat
的所有属性都不是聚集的(non-aggregated)。你必须明确的列出所有的非聚集属性。