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<Object[]> 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<Object[]> 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<Object[]> 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进行投影查询来封装查询结果中的关系数据。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 引出 •请思考如下问题? –查询所有员工的每个月工资总和,平均工资? –查询工资最高和最低的工资是多少? –查询公...
    C_cole阅读 12,041评论 0 3
  • 5.多表查询 多表查询 目的:从多张表获取数据 前提:进行连接的多张表中有共同的列 等连接 通过两个表具有相同意义...
    乔震阅读 5,283评论 0 0
  • ORACLE自学教程 --create tabletestone ( id number, --序号usernam...
    落叶寂聊阅读 4,831评论 0 0
  • 查询是数据的一个重要操作。用户发送查询请求,经编译软件变异成二进制文件供服务器查询,后返回查询结果集给用户,查询会...
    产品小正阅读 5,312评论 0 2
  • oracle 数据库的scott帐号。 <>作为查询条件时,可以使用!= 来替换。 SQL> select * f...
    庄栋栋阅读 6,891评论 0 0

友情链接更多精彩内容