选择大部分早期员工

时间:2013-02-05 15:03:57

标签: sql oracle

我有以下问题:

  

为每个位置城市选择大部分早期员工,显示位置城市和即将到来的日期

我试过跟随一个

select  e.hiredate  as LOC,d.loc  as COMDATE
from    emp e, dept  d
where   e.hiredate in (
    select  min(e.hiredate) 
    from  emp e
    group by d.loc
)

显示以下结果

17-DEC-80   NEW YORK
17-DEC-80   DALLAS
17-DEC-80   CHICAGO
17-DEC-80   BOSTON

但问题是只有一个17-DEC-80,所以它意味着它会重复,我该如何解决?

3 个答案:

答案 0 :(得分:1)

结果是来自cross join的产品,您需要提供表之间的关系。前

SELECT  e.hiredate AS LOC,
        d.loc AS COMDATE
FROM    emp e
        INNER JOIN dept d 
            ON e.deptno = d.deptno
WHERE   e.hiredate IN 
        (
            SELECT min(e.hiredate)
            FROM emp e
            GROUP BY d.loc
        )

答案 1 :(得分:1)

如果您需要选择其他字段以及hiredate / location,您可以使用rank()分析:

select *
  from (select e.*, d.loc, rank() over (partition by d.loc order by e.hiredate) rnk
          from emp e
               inner join dept d
                       on d.deptno = e.deptno
       )
 where rnk = 1;

如果您只需要hiredate和location,请使用min()

select min(e.hiredate), d.loc
  from emp e
       inner join dept d
               on d.deptno = e.deptno
 group by d.loc;

答案 2 :(得分:1)

您的查询中有交叉联接或笛卡尔积,因为它们没有加入emp和dept表。 JW的第一个查询的简单版本。别名不正确......:

select  e.hiredate  as LOC,d.loc  as COMDATE
 from    scott.emp e, scott.dept  d
 where e.deptno= d.deptno -- Cartesian if you not join --
 and e.hiredate in (
     select  min(e.hiredate) 
      from  scott.emp e
      group by d.loc
   )
  /