You are on page 1of 2

http://download.oracle.com/docs/cd/B13789_01/server.

101/b10759/statements_100
02.htm#i2066378

Using the GROUP BY CUBE Clause: Example
To return the number of employees and their average yearly salary across all possible
combinations of department and job category, issue the following query on the sample
tables hr.employees and hr.departments:
SELECT DECODE(GROUPING(department_name), 1, 'All Departments',
department_name) AS department_name,
DECODE(GROUPING(job_id), 1, 'All Jobs', job_id) AS job_id,
COUNT(*) "Total Empl", AVG(salary) * 12 "Average Sal"
FROM employees e, departments d
WHERE d.department_id = e.department_id
GROUP BY CUBE (department_name, job_id);

DEPARTMENT_NAME JOB_ID Total Empl Average Sal
------------------------------ ---------- ---------- -----------
Accounting AC_ACCOUNT 1 99600
Accounting AC_MGR 1 144000
Accounting All Jobs 2 121800
Administration AD_ASST 1 52800
. . .
All Departments ST_MAN 5 87360
All Departments All Jobs 107 77798.1308

Using the GROUPING SETS Clause: Example
The following example finds the sum of sales aggregated for three precisely specified
groups:
• (channel_desc, calendar_month_desc, country_id)
• (channel_desc, country_id)
• (calendar_month_desc, country_id)

Without the GROUPING SETS syntax, you would have to write less efficient queries with
more complicated SQL. For example, you could run three separate queries
and UNION them, or run a query with aCUBE(channel_desc, calendar_month_desc,
country_id) operation and filter out five of the eight groups it would generate.
SELECT channel_desc, calendar_month_desc, co.country_id,
TO_CHAR(sum(amount_sold) , '9,999,999,999') SALES$
FROM sales, customers, times, channels, countries co
WHERE sales.time_id=times.time_id
AND sales.cust_id=customers.cust_id
AND sales.channel_id= channels.channel_id
AND customers.country_id = co.country_id
AND channels.channel_desc IN ('Direct Sales', 'Internet')
AND times.calendar_month_desc IN ('2000-09', '2000-10')

378.388.310 Internet US 3.622 2000-10 US 4. (channel_desc.571 Internet 2000-09 US 1.240 Internet 2000-10 US 1. ( calendar_month_desc. co.263 Internet UK 1.802.country_id IN ('UK'.557 Direct Sales 2000-10 US 2.744.835.797 2000-10 UK 2. co. -. CHANNEL_DESC CALENDAR CO SALES$ -------------------.country_id).706 Internet 2000-09 UK 911.625.893.289. co.788.567.country_id).-------------- Direct Sales 2000-09 UK 1.732.177 Direct Sales US 5.051 Direct Sales 2000-09 US 2. AND co.country_id) ).126 Direct Sales 2000-10 UK 1.739 Internet 2000-10 UK 876.766. 'US') GROUP BY GROUPING SETS( (channel_desc.264. -------.753 Direct Sales UK 2.908. calendar_month_desc.993 2000-09 UK 2.865 2000-09 US 4.459 .