Search code examples
sqloracle-databaserollup

Oracle: replace "rollup" in query with something else


I need to rewrite a simple query without rollup function. Could you help me?

This is an original query:

  SELECT e.department_id, 
         e.job_id, 
         SUM(e.salary)
    FROM EMPLOYEES e
GROUP BY ROLLUP(e.department_id, e.job_id);

I guess it is possible to rewrite using UNION statement, yea?


Solution

  • The following should return the same result as a rollup, but with worse performance and less controll over the "levels".

    select e.department_id
          ,e.job_id
          ,SUM(e.salary)
      from EMPLOYEES e
     group 
        by e.department_id
          ,e.job_id
    union all
    select e.department_id
          ,null
          ,SUM(e.salary)
      from EMPLOYEES e
     group 
        by e.department_id
    union all
    select null
          ,null
          ,SUM(e.salary)
      from EMPLOYEES e;