Oracle CONNECT BY和MAX

时间:2014-01-24 16:45:14

标签: oracle

我很难将MAX集成到查询中,并且非常感谢任何帮助。

基本上我正在努力实现的目标是:列出一名主管的主管的受监督员工以及他们最新的“一天”打卡时间。

我无法做到的部分是MAX(休息日)部分。

这是我到目前为止工作得很好的部分

SELECT EMPLOYEE.NUMBER, 
       EMPLOYEE.NAME, 
       S.NAME AS SUPERVISOR,
       EMPLOYEE.HIRE_DATE
FROM EMPLOYEE
LEFT JOIN EMPLOYEE_NUMBER ON EMPLOYEE_NUMBER.NUMBER = EMPLOYEE.SUPERVISOR_NUMBER
LEFT JOIN EMPLOYEE S ON S.NUMBER = EMPLOYEE.SUPERVISOR_NUMBER
WHERE LEVEL =2 
START WITH EMPLOYEE_NUMBER.USERID = (ID OF SUPERVISOR HERE)
CONNECT BY PRIOR EMPLOYEE.NUMBER = EMPLOYEE.SUPERVISOR_NUMBER

这部分有效,并为我提供了我需要的基本输入。但是,我还需要为每位员工列出他/她最新的“休息日”。

以下是我尝试过的尝试不起作用

SELECT EMPLOYEE.NUMBER, 
       EMPLOYEE.NAME, 
       S.NAME AS SUPERVISOR,
       EMPLOYEE.HIRE_DATE,
       MAX(EMPLOYEE_TIME.DATE_OUT)
FROM EMPLOYEE
LEFT JOIN EMPLOYEE_NUMBER ON EMPLOYEE_NUMBER.NUMBER = EMPLOYEE.SUPERVISOR_NUMBER
LEFT JOIN EMPLOYEE S ON S.NUMBER = EMPLOYEE.SUPERVISOR_NUMBER
LEFT JOIN EMPLOYEE_TIME ON EMPLOYEE_TIME.EMPLOYEE_NUMBER = EMPLOYEE.EMPLOYEE_NUMBER
WHERE LEVEL =2 
START WITH EMPLOYEE_NUMBER.USERID = (ID OF SUPERVISOR HERE)
CONNECT BY PRIOR EMPLOYEE.NUMBER = EMPLOYEE.SUPERVISOR_NUMBER
GROUP BY
       EMPLOYEE.NUMBER, 
       EMPLOYEE.NAME, 
       S.NAME,
       EMPLOYEE.HIRE_DATE
HAVING MAX(EMPLOYEE_TIME.DATE_OUT) >= SYSDATE-60

它不会抛出任何错误,它只会继续处理。我猜一些东西必须循环,但我无法理解。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在加入时间表时,您的查询稍有变化,无需在CONNECT BY时加入,而是将其分开。

SELECT NUMBER, 
       EMPLOYEE_NAME, 
       SUPERVISOR,
       HIRE_DATE,
       MAX(TIME.DATE_OUT)
FROM
(SELECT NUMBER, 
       EMPLOYEE.NAME AS EMPLOYEE_NAME,
       S.NAME AS SUPERVISOR,
       EMPLOYEE.HIRE_DATE
FROM EMPLOYEE
LEFT JOIN EMPLOYEE_NUMBER ON EMPLOYEE_NUMBER.NUMBER = EMPLOYEE.SUPERVISOR_NUMBER
LEFT JOIN EMPLOYEE S ON S.NUMBER = EMPLOYEE.SUPERVISOR_NUMBER
WHERE LEVEL =2 
START WITH EMPLOYEE_NUMBER.USERID = (ID OF SUPERVISOR HERE)
CONNECT BY PRIOR EMPLOYEE.NUMBER = EMPLOYEE.SUPERVISOR_NUMBER) EMP_SUP
INNER JOIN EMPLOYEE_TIME TIME
ON( EMP_SUP.NUMBER = TIME.NUMBER)
GROUP BY
       NUMBER, 
       EMPLOYEE_NAME, 
       SUPERVISOR,
       HIRE_DATE
HAVING MAX(DATE_OUT) >= SYSDATE-60