MIN子句麻烦

时间:2012-10-04 03:09:40

标签: sql oracle10g

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

还有另一个名为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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 )

您可以将其读作“对于每位员工,如果他的出生日期等于其所在部门的最大出生日期,则将其退回”。

答案 2 :(得分:0)

如果我理解正确,您需要的是the FIRST_VALUE analytic function

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
        )
;