GROUPING SETS: get the subtotal rows : GROUPING SETS « Analytical Functions « Oracle PL / SQL






GROUPING SETS: get the subtotal rows



SQL> CREATE TABLE employee(
  2    employee_id INTEGER,
  3    division_id CHAR(3),
  4    job_id CHAR(3),
  5    first_name VARCHAR2(10) NOT NULL,
  6    last_name VARCHAR2(10) NOT NULL,
  7    salary NUMBER(6, 0)
  8  );

Table created.

SQL>
SQL> insert into employee (EMPLOYEE_ID,division_id,JOB_ID,FIRST_NAME,LAST_NAME,SALARY)
  2                 values(1, 'BUS','PRE','James','Smith','800000');

1 row created.

SQL> insert into employee (EMPLOYEE_ID,division_id,JOB_ID,FIRST_NAME,LAST_NAME,SALARY)
  2                 values(2, 'SAL','MGR','Ron','Johnson','350000');

1 row created.

SQL> insert into employee (EMPLOYEE_ID,division_id,JOB_ID,FIRST_NAME,LAST_NAME,SALARY)
  2                 values(3, 'SAL','WOR','Fred','Hobbs','140000');

1 row created.

SQL> insert into employee (EMPLOYEE_ID,division_id,JOB_ID,FIRST_NAME,LAST_NAME,SALARY)
  2                 values(4, 'SUP','MGR','Susan','Jones','200000');

1 row created.

SQL> insert into employee (EMPLOYEE_ID,division_id,JOB_ID,FIRST_NAME,LAST_NAME,SALARY)
  2                 values(5, 'SAL','WOR','Rob','Green','350000');

1 row created.

SQL>
SQL> select * from employee;

EMPLOYEE_ID DIV JOB FIRST_NAME LAST_NAME      SALARY
----------- --- --- ---------- ---------- ----------
          1 BUS PRE James      Smith          800000
          2 SAL MGR Ron        Johnson        350000
          3 SAL WOR Fred       Hobbs          140000
          4 SUP MGR Susan      Jones          200000
          5 SAL WOR Rob        Green          350000

SQL>
SQL>
SQL>
SQL> --Using the GROUPING SETS Clause
SQL>
SQL> --GROUPING SETS: get the subtotal rows. 
       The following example uses GROUPING SETS to get the subtotals for 
       salaries by division_id and job_id:
SQL>
SQL> SELECT division_id, job_id, SUM(salary)
  2  FROM employee
  3  GROUP BY GROUPING SETS(division_id, job_id);

DIV JOB SUM(SALARY)
--- --- -----------
SUP          200000
SAL          840000
BUS          800000
    MGR      550000
    PRE      800000
    WOR      490000

6 rows selected.

SQL>
SQL>
SQL>
SQL>
SQL> drop table employee;

Table dropped.

SQL>
SQL>
           
       








Related examples in the same category

1.Use GROUPING SETS and RANK() to get just the sales amount subtotal rankings