
How to use sum and avg function in HQL?

HQL supports many aggregate functions. Sum and avg are some of them.
sum() function returns summation of specified field in the table.
avg() function returns average of specified field in the table.
Example:
package net.roseindia.main;
import net.roseindia.util.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class DistinctCountHQL {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
String sumHql = "Select sum(emp.salary) FROM Employee emp";
String avgHql = "Select avg(emp.salary) FROM Employee emp";
Query sumQuery = session.createQuery(sumHql);
Query avgQuery = session.createQuery(avgHql);
System.out.println("Sum of all salary : " + sumQuery.list().get(0));
System.out.println("Average of salary : " + avgQuery.list().get(0));
}
}
Output:
Hibernate: select sum(employee0_.salary) as col_0_0_ from employee employee0_ Sum of all salary : 275000 Hibernate: select avg(employee0_.salary) as col_0_0_ from employee employee0_ Average of salary : 68750.0
Description: This example calculates sum of salary as- sum(emp.salary) and average of salary as- avg(emp.salary)