Search code examples
oracle-databasecountgroup-bydistincthaving-clause

Oracle Query: Get distinct names having count greater than a threshold


I have a table having schema given below

EmpID,MachineID,Timestamp
    1,        A,01-Nov-13
    2,        A,02-Nov-13
    3,        C,03-Nov-13
    1,        B,02-Nov-13
    1,        C,04-Nov-13
    2,        B,03-Nov-13
    3,        A,02-Nov-13

Desired Output:

EmpID,MachineID
    1,        A
    1,        B
    1,        C
    2,        A
    2,        B
    3,        A
    3,        C

So basically, I want to find the Emp who have used more than one machines in the given time period.

The query I am using is

select EmpID,count(distinct(MachineID)) from table 
where Timestamp between '01-NOV-13' AND '07-NOV-13'
group by EmpID having count(distinct(MachineID)) > 1
order by count(distinct(MachineID)) desc;

This query is given me output like this

EmpID,count(distinct(MachineID))
    1,                        3
    2,                        2
    3,                        2   

Can anyone help with making changes to get the output like described above in my question.


Solution

  • One possible solution:

    CREATE TABLE emp_mach (
      empid NUMBER,
      machineid VARCHAR2(1),
      timestamp_val DATE
    );
    
    INSERT INTO emp_mach VALUES (1,'A', DATE '2013-11-01');
    INSERT INTO emp_mach VALUES (2,'A', DATE '2013-11-02');
    INSERT INTO emp_mach VALUES (3,'C', DATE '2013-11-03');
    INSERT INTO emp_mach VALUES (1,'B', DATE '2013-11-02');
    INSERT INTO emp_mach VALUES (1,'C', DATE '2013-11-04');
    INSERT INTO emp_mach VALUES (2,'B', DATE '2013-11-03');
    INSERT INTO emp_mach VALUES (3,'A', DATE '2013-11-02');
    
    COMMIT;
    
    SELECT DISTINCT empid, machineid
      FROM emp_mach
    WHERE empid IN (
      SELECT empid
        FROM emp_mach
      WHERE timestamp_val BETWEEN DATE '2013-11-01' AND DATE '2013-11-07'
      GROUP BY empid
      HAVING COUNT(DISTINCT machineid) > 1
    )
    ORDER BY empid, machineid;
    

    (I've changed the name of the timestamp column to timestamp_val)

    Output:

         EMPID MACHINEID
    ---------- ---------
             1 A         
             1 B         
             1 C         
             2 A         
             2 B         
             3 A         
             3 C