You can use the GROUP_ID() function to remove duplicate rows returned by a GROUP BY clause : GROUPING_ID « Analytical Functions « Oracle PL / SQL






You can use the GROUP_ID() function to remove duplicate rows returned by a GROUP BY clause



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> --Using the GROUP_ID() Function
SQL>
SQL> --You can use the GROUP_ID() function to remove duplicate rows returned by a GROUP BY clause. 
GROUP_ID() doesnt accept any parameters. 
If n duplicates exist for a particular grouping, GROUP_ID returns numbers in the range 0 to n-1.
SQL>
SQL>
SQL> SELECT division_id, job_id, GROUP_ID(), SUM(salary)
  2  FROM employee
  3  GROUP BY division_id, ROLLUP(division_id, job_id);

DIV JOB GROUP_ID() SUM(SALARY)
--- --- ---------- -----------
BUS PRE          0      800000
SAL MGR          0      350000
SAL WOR          0      490000
SUP MGR          0      200000
BUS              0      800000
SAL              0      840000
SUP              0      200000
BUS              1      800000
SAL              1      840000
SUP              1      200000

10 rows selected.

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

Table dropped.

SQL>
           
       








Related examples in the same category

1.An Example Query that Illustrates the Use of GROUPING_ID()
2.One useful application of GROUPING_ID() is to filter rows using a HAVING clause
3.Eliminate duplicate rows using a HAVING clause that only allows rows whose GROUP_ID() is 0