15.12. group by 子句
优质
小牛编辑
130浏览
2023-12-01
一个返回聚集值(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)。你必须明确的列出所有的非聚集属性。