tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Hibernate > Hibernate Query Language > Sum Average Aggregate Functions

Sum Average Aggregate Functions 

The following example shows using HQL sum, avg and count aggregate functions. Refer first example for the configuration and mapping.

File Name  :  
com/bethecoder/tutorials/hibernate/basic/tests/HQLSumAvgCountTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.hibernate.basic.tests;

import java.util.Arrays;
import org.hibernate.Session;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;

public class HQLSumAvgCountTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    
    String HQL_QUERY = "select sum(employeeCount), avg(employeeCount), count(*) from Company comp";
    Object[] row = (Object[]) session.createQuery(HQL_QUERY).uniqueResult();    
    System.out.println(Arrays.toString(row));

    System.out.println("Total employee count : " + row[0]);
    System.out.println("Average Employee count : " + row[1]);
    System.out.println("Company count : " + row[2]);
    
    session.getTransaction().commit();
    session.close();
  }

}
   

It gives the following output,
[402944, 40294.4, 10]
Total employee count : 402944
Average Employee count : 40294.4
Company count : 10



 
  


  
bl  br