HQL分组查询

HQL查询语句使用group by 子句进行分组查询,使用having子句筛选分组结果。

按职位统计员工个数

 Long count=(Long)this.getCurrentSession().createQuery("select count(e.id) from Emp  e group by e.job").uniqueResult();

Hibernate:
select
count(emp0_.empNo) as col_0_0_
from
project.Emp emp0_
group by
emp0_.job

统计各个部门的平均工资

List avg=this.getCurrentSession().createQuery("select e.department.deptName,avg (e.salary) from Emp e group by e.department.deptName").list();

Hibernate:
select
department1_.deptName as col_0_0_,
avg(emp0_.salary) as col_1_0_
from
project.Emp emp0_,
project.Department department1_
where
emp0_.deptNo=department1_.deptNo
group by
department1_.deptName

统计各个职位的最低工资和最高工资

   List maxMin=this.getCurrentSession().createQuery("select e.job,max (e.salary),min (e.salary) from Emp e group by e.job").list();

Hibernate:
select
emp0_.job as col_0_0_,
max(emp0_.salary) as col_1_0_,
min(emp0_.salary) as col_2_0_
from
project.Emp emp0_
group by
emp0_.job

统计平均工资高于4000元的部门名称,输出部门名称,部门平均工资

 List avg=this.getCurrentSession().createQuery("select e.department.deptName,avg (e.salary) from Emp e group by e.department.deptName having avg (e.salary)>4000").list();

Hibernate:
select
department1_.deptName as col_0_0_,
avg(emp0_.salary) as col_1_0_
from
project.Emp emp0_,
project.Department department1_
where
emp0_.deptNo=department1_.deptNo
group by
department1_.deptName
having
avg(emp0_.salary)>4000

使用select子句时,Hibernate返回的查询结果为关系数据而不是持久化对象,不会占用Session缓存。为了方便访问,可以定义一个JavaBean进行投影查询来封装查询结果中的关系数据。

你可能感兴趣的:(HQL分组查询)