根据特定条件提取员工记录

llmtgqce  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(211)

我有一个员工数据库,里面有他们在公司的工作经历。
样本数据-

+----+----------+------------+
| ID |   Date   |   Event    |
+----+----------+------------+
|  1 | 20190807 | Hired      |
|  1 | 20191209 | Promoted   |
|  1 | 20200415 | Terminated |
|  2 | 20180901 | Hired      |
|  2 | 20191231 | Terminated |
|  3 | 20180505 | Hired      |
|  3 | 20190630 | Promoted   |
+----+----------+------------+

我想提取升职后被解雇的员工名单。在上面的示例中,查询应该返回id 1。
如果有帮助的话,我正在使用ssms17。

shyt4zoc

shyt4zoc1#

您可以尝试使用lag()
演示

select distinct ID from
(
select *,lag(event) over(partition by id order by dateval) as prevval
from t
)A where prevval='Promoted'
jdg4fx2g

jdg4fx2g2#

如果你想立即后,那么你会使用 lag() . 如果您想在之后的任何时间使用聚合:

select id
from t
group by id
having max(case when event = 'Promoted' then dateval end) < max(case when event = 'Terminated' then dateval end);

使用 lag() ,代码如下所示:

select id
from (select t.*, lag(event) over (partition by id order by dateval) as prev_event
      from t
     ) t
where prev_event = 'Promoted' and event = 'Terminated';
nxagd54h

nxagd54h3#

一个简单的 exists check也可以解决这个简单的需求。
演示

select * from table1 a
where event='Terminated'
and exists(select 1 from table1 b where a.ID = b.ID  and event='Promoted');

输出:

ID  date1       event
1   20191209    Terminated

我们甚至可以比较相关子查询中的事件日期,如演示链接所示。

相关问题