0

我无法显示每个部门最年轻的员工。

还有一个名为 的表department,它简单地表示部门编号和部门名称。我也尝试过 WHERE EXISTS 子句,但没有运气。

   SELECT emp_department_number, 
          emp_name, 
          MIN(TRUNC(((current_date - emp_dateofbirth)/(365.25)))) "age" 
     FROM employee
 GROUP BY emp_department_number, emp_name
 ORDER BY emp_department_number;

我也有这个,但它会产生相同的结果..

 SELECT emp_department_number, emp_name, min(TRUNC(((current_date -      emp_dateofbirth)/(365.25)))) "age" from employee
 JOIN department
 ON dpt_num=emp_department_number
 WHERE EXISTS (select min(emp_dateofbirth) from employee)
 GROUP BY emp_department_number, emp_name
 order by emp_department_number;



 EMP_DEPARTMENT_NUMBER EMP_NAME                        age
 -------------- ------------------------------ ----------
 1              Ramon, Emma                           25
 1              Tin, Rina                             69
 3              Mason, John                           68
 3              Roberson, Wayne                       50
 3              Zan, Shelis                           51
 7              Hockman, Ronnie                       62
 7              Lam, Annie                            37
 7              Smith, Ramon                          60
4

3 回答 3

1

由于您使用的是 Oracle,因此您可以使用它MONTHS_BETWEEN来计算确切的年龄。而求最小的可以跳过年龄计算emp_dateofbirth直接使用。

 SELECT emp_department_number, emp_name
      , trunc(MONTHS_BETWEEN(emp_dateofbirth, current_date)/12) as age
   from employee e
  WHERE e.emp_dateofbirth = (
        SELECT MAX(emp_dateofbirth) 
          FROM employee x
         WHERE x.emp_department_number = e.emp_department_number )

您可以阅读为“对于每个员工,如果他的出生日期等于他所在部门的最大出生日期,则返回它”。

于 2012-10-04T09:02:47.813 回答
1

您可以使用ROW_NUMBER()分析函数来执行此操作(我在部门表中添加了潜在连接以获取名称):

SELECT dept_name, empl, age
FROM (
  SELECT EMP_DEPARTMENT_NUMBER AS dept,
       EMP_NAME AS empl,
       TRUNC((CURRENT_DATE - emp_dateofbirth) / 365.25) AS age,
       ROW_NUMBER() OVER (PARTITION BY EMP_DEPARTMENT_NUMBER ORDER BY emp_dateofbirth ASC) AS rn
  FROM employee
) E
JOIN department d
  ON e.dept = d.dept_id
WHERE rn = 1
于 2012-10-04T04:03:43.613 回答
0

如果我理解正确,您需要的是分析FIRST_VALUE功能

SELECT emp_department_number,
       emp_name,
       TRUNC((CURRENT_DATE - emp_dateofbirth) / 365.25) age
  FROM employee
 WHERE emp_num IN
        ( SELECT FIRST_VALUE(emp_num) OVER
                    ( PARTITION BY emp_department_number
                          ORDER BY emp_dateofbirth DESC
                    )
            FROM employee
           GROUP
              BY emp_department_number
        )
;
于 2012-10-04T03:51:46.017 回答