Question

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.

Was it helpful?

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  

OTHER TIPS

you did the hardest. Your query has to be used to filter out the results:

SELECT t1.empid, t1.machineid
FROM
    table t1
WHERE
    EXIST (
        SELECT
            empid
        FROM table t2
        WHERE 
            timestamp BETWEEN '01-NOV-13' AND '07-NOV-13'
        AND t2.empid = t1.empid
        GROUP BY empid HAVING COUNT(distinct(machineid)) > 1
)
ORDER BY empid, machineid;

edit: posted a few secs after Przemyslaw Kruglej. I'll leave it here since it is just another alternative (using EXIST instead of IN)

   SELECT * FROM
        (SELECT DISTINCT(EmpID),COUNT(*) AS NumEMP
        from TableA
        WHERE Timestamp between '01-NOV-13' AND '07-NOV-13'
        group by EmpID 
        order by EmpID
        )
   WHERE NumEmp >= 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top