选择最近加入国王的所有员工

时间:2014-05-06 17:12:36

标签: sql sql-server-2008 tsql

emp table

empno ename    sal    deptno mgr      job       comm  hiredate 

7369  SMITH   800.0000  20  7902      CLERK           1980-12-17 00:00:00.000
7499  ALLEN1  600.0000  30  7698      SALESMAN  300   1981-02-20 00:00:00.000
7521  WARD    1250.0000 30  7698      SALESMAN  500   1981-02-22 00:00:00.000
7566  JONES   2975.0000 20  7839      MANAGER         1981-04-02 00:00:00.000
7654  MARTIN  1250.0000 30  7839      SALESMAN  1400  1981-09-28 00:00:00.000
7698  BLAKE   2850.0000 30  7839      MANAGER         1981-05-01 00:00:00.000
7782  CLARK   2450.0000 10  7839      MANAGER         1981-06-09 00:00:00.000
7788  SCOTT   3000.0000 20  7566      ANALYST         1987-04-19 00:00:00.000
7839  KING    5000.0000 10            PRESIDENT       1981-11-17 00:00:00.000
7844  TURNER  1500.0000 30  7698      SALESMAN  0     1981-09-08 00:00:00.000
7876  ADAMS   1100.0000 20  7788      CLERK           1987-05-23 00:00:00.000
7900  JAMES   950.0000  30  7698      CLERK           1981-12-03 00:00:00.000
7902  FORD    3000.0000 20  7566      ANALYST         1981-12-03 00:00:00.000
7934  MILLER  1300.0000 10  7782      CLERK           1982-01-23 00:00:00.000

这是我到目前为止所做的:

select e.*,datediff(dd,e.hiredate,getdate()) min_exp 
from emp e 
join emp e1 on e.mgr=e1.empno1 
where e1.empname='king' 
  and datediff(dd,e.hiredate,getdate()) = 
      (
          select min(datediff(dd,e.hiredate,getdate())) from emp
      ) 

2 个答案:

答案 0 :(得分:0)

因此,如果您只需要在King被雇用后雇用的员工名单,只需使用King的雇用日期作为过滤器。

select e.*,datediff(dd,e.hiredate,getdate()) min_exp 
from emp e 
where e.hiredate > (SELECT hiredate FROM emp WHERE ename = 'king') 

测试声明并根据需要进行调整。我没有验证它。

答案 1 :(得分:0)

select top(1) from (
    select * from emp 
    where empname='king' order by hiredate desc
) t;