Sql 显示最后一位被雇用的员工
我需要找到最近雇佣的员工 例如我有一张桌子 输入 需要在最后雇用的员工的一行中添加带“*”的第三列 输出Sql 显示最后一位被雇用的员工,sql,database,oracle,Sql,Database,Oracle,我需要找到最近雇佣的员工 例如我有一张桌子 输入 需要在最后雇用的员工的一行中添加带“*”的第三列 输出 ---------------------------------- | name | hire_date | maxdate | ---------------------------------- | Michael | 11-JAN-2010| | | Eugene | 20-DEC-2018| * | ----------------------
----------------------------------
| name | hire_date | maxdate |
----------------------------------
| Michael | 11-JAN-2010| |
| Eugene | 20-DEC-2018| * |
----------------------------------
在Oracle的最新版本中,请使用
按顺序
和获取
:
select e.*
from employees e
order by hire_date desc
fetch first 1 row only;
在早期版本中,这通常使用子查询实现:
select e.*
from (select e.*
from employees e
order by hire_date desc
)
where rownum = 1;
这两个都只返回一行--您的问题是单数形式的。如果存在重复项,则会返回所有最新员工的变体。分析功能可能有助于:
SQL> with test (name, hire_date) as
2 (select 'Michael', date '2010-01-11' from dual union all
3 select 'Eugene' , date '2018-12-20' from dual
4 )
5 select name,
6 hire_date,
7 case when rank() over (order by hire_date desc) = 1 then '*' else null end maxdate
8 from test;
NAME HIRE_DATE MAXDATE
------- ---------- -------
Eugene 20-12-2018 *
Michael 11-01-2010
SQL>
还有一种选择,没有分析功能:
SQL> with test (name, hire_date) as
2 (select 'Michael', date '2010-01-11' from dual union all
3 select 'Eugene' , date '2018-12-20' from dual
4 ),
5 maxdate as
6 (select max(hire_date) max_hire_date
7 from test
8 )
9 select t.name,
10 t.hire_date,
11 case when t.hire_date = m.max_hire_date then '*' else null end maxdate
12 from test t cross join maxdate m;
NAME HIRE_DATE MAXDATE
------- ---------- --------
Michael 11-01-2010
Eugene 20-12-2018 *
SQL>
试试这个
Select hire_date, name from( Select
hire_date, name, row_number
() over (partition by hire_date order
by hire_date desc) rn
from
Table where hire_date
= (select max(hire_date)
From table)) where rn=1
但是,如果我在一天内雇佣了两名员工,你就偏离了你的实际要求。这是Gordon发布的最好方法,如果你想让多个员工在同一个日期工作,这是最简单的步骤,只需在子查询中使用max(hiredate),你就可以得到你想要的结果检查我的解决方案我如何做到这一点而不过度你可以将hire_date列值与同一列的最大值进行比较。我已经编辑了我的答案并添加了一些代码。请看一看。
Select hire_date, name from( Select
hire_date, name, row_number
() over (partition by hire_date order
by hire_date desc) rn
from
Table where hire_date
= (select max(hire_date)
From table)) where rn=1