1

我有一个表,其架构如下

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

期望的输出:

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

所以基本上,我想找到在给定时间段内使用过不止一台机器的 Emp。

我正在使用的查询是

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;

这个查询给了我这样的输出

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

任何人都可以帮助进行更改以获取上述问题中所述的输出。

4

3 回答 3

2

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  
于 2013-11-07T01:30:24.067 回答
1

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)

于 2013-11-07T01:31:11.803 回答
1
   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
于 2016-08-31T18:10:06.137 回答