Follow Us on Twitter

Rollup as aggregation enhancement

by Jan Thuis on March 17, 2010 · 0 comments

This morning I wrote a query with a GROUP BY clause. Not really complicated. Here’s a worked example:

select department_id department
      ,job_id job
      ,round(avg(salary)) average
      ,round(sum(salary)) total
 from hr.employees
 where department_id in ( 80 ,50)
 group by job_id,department_id

The result, the total and the average salary of two departments grouped by department and job.

DEPARTMENT JOB AVERAGE TOTAL
50 ST_MAN 7280 36400
80 SA_REP 8397 243500
50 SH_CLERK 3215 64300
80 SA_MAN 12200 61000
50 ST_CLERK 2785 55700

What’s missing in this report is the total and average salaries of the entire group and the total and average salary per department, regardless of the job.

After some thought and typing I came up with this solution:

select department_id department
      ,job_id job
      ,round(avg(salary)) average
      ,round(sum(salary)) total
  from hr.employees
 where department_id in( 80 ,50)
 group by department_id, job_id
 union all
select department_id department
      ,null job
      ,round(avg(salary)) average
      ,round(sum(salary)) total
  from hr.employees
 where department_id in( 80 ,50)
 group by department_id
 union all
select null department
      ,null job
      ,round(avg(salary)) average
      ,round(sum(salary)) total
  from hr.employees
 where department_id in( 80 ,50)

The result of this query:

DEPARTMENT JOB AVERAGE TOTAL
50 ST_MAN 7280 36400
50 SH_CLERK 3215 64300
50 ST_CLERK 2785 55700
50 3476 156400
80 SA_MAN 12200 61000
80 SA_REP 8397 243500
80 8956 304500
5834 460900

Quite a long query. There must be a better solution I thought. Perhaps one of the analytic functions. Eventually I found the solution, with the same rusult of course in (one of) the aggregation enhancements, called, ‘ROLLUP’.

select department_id department
      ,job_id job
      ,round(avg(salary)) average
      ,round(sum(salary)) total
  from hr.employees
 where department_id in( 80 ,50)
 group by rollup (department_id,job_id)

For me it was an eyeopener, so beautiful, so compact, whow!

Ratings:
VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)

Leave a Comment

 

Previous post:

Next post:

About Whitehorses
Company profile
Services
Technology

Whitehorses website

Home page
Whitebooks
Jobs

Follow us
Blog post RSS
Comment RSS
Twitter