选择Oracle中最老和最年轻的员工

时间:2019-07-14 00:28:31

标签: sql oracle

我想选择工作场所中年龄最大和最年轻的员工。年龄最大和年龄最小的是他们的工作经验。 我提到了SQL Server的先前问题,并如下修改了我的代码,但出现错误:

  

无效的标识符。

我想知道我对更改代码有什么建议吗?

 SELECT d.Dtable_name,
        RANK() OVER(ORDER BY SUM(ROUND((SYSDATE - e.hire_date) / 365.24,0)) DESC) AS yrsexperience
   FROM Dtable_department d
   LEFT JOIN Etable_employee e
     ON d.department_id=e.department_id
WHERE yrsexperience =(SELECT MAX(d.department_name) KEEP(DENSE_RANK FIRST ORDER BY SUM(ROUND((SYSDATE - e.hire_date) / 365.24,0)) DESC) AS yrsexperience) AS Oldest)FROM Etable_employee e)

OR yrsexperience =(SELECT
       MIN(d.department_name) KEEP(DENSE_RANK LAST  ORDER BY SUM(ROUND((SYSDATE - e.hire_date) / 365.24,0)) DESC) AS yrsexperience) AS Youngest
  FROM Etable_employee e)

更新

我参考下面的答案后编辑了代码,但它抛出了错误:

  

找不到FROM。

2 个答案:

答案 0 :(得分:1)

您可以使用FIRSTLAST聚合函数。

SELECT MAX(name) KEEP(DENSE_RANK FIRST ORDER BY yrs_experience ) AS Youngest,
       MAX(name) KEEP(DENSE_RANK LAST  ORDER BY yrs_experience ) AS Oldest
  FROM etable_employee;

答案 1 :(得分:0)

看来YRSEXPERIENCEETABLE_EMPLOYEE上的一个字段。鉴于此,我希望如此

SELECT *
  FROM ETABLE_EMPLOYEE
  WHERE YRS_EXPERIENCE IN (SELECT MIN(YRS_EXPERIENCE) FROM ETABLE_EMPLOYEE
                           UNION ALL
                           SELECT MAX(YRS_EXPERIENCE) FROM ETABLE_EMPLOYEE)

将为您提供所需的内容。

编辑

根据更多信息:

SELECT SYSDATE - e.HIRE_DATE AS YRS_EXPERIENCE
  FROM ETABLE_EMPLOYEE e
  WHERE SYSDATE - e.HIRE_DATE IN (SELECT MIN(SYSDATE - HIRE_DATE) FROM ETABLE_EMPLOYEE
                                  UNION ALL
                                  SELECT MAX(SYSDATE - HIRE_DATE) FROM ETABLE_EMPLOYEE)

dbfiddle here