繁体   English   中英

Oracle SQL 代码列出一个人的就业事件和另外 2 列专门列出以前的事件和日期

[英]Oracle SQL code to list a persons employment events and another 2 columns devoted listing the prior event and date

所以我有一个充满就业事件的人的数据库,我正在尝试在 SQL 中构建一个报告,该报告将提取以下内容:

姓名、雇佣事件、雇佣事件日期、在该事件之前发生的雇佣事件以及最近事件的日期。

对数据进行组织,以便每个事件都是一行。 因此,如果我提取名为 John Smith 的参与者的就业历史,我将得到 output(按事件日期排序):

Name            Event              Date of Event
John Smith      Terminated         5/13/2017
John Smith      Return from Leave  4/13/2017
John Smith      Paid Leave         3/31/2017
John Smith      Hire               1/1/2000

我的目标是获得以下 output:

Name            Event              Date of Event     Prior Event          Date of prior event
John Smith      Terminated         5/13/2017         Return from Leave    4/13/2017
John Smith      Return from Leave  4/13/2017         Paid Leave           3/31/2017
John Smith      Paid Leave         3/31/2017         Hire                 1/11/2000
John Smith      Hire               1/1/2000          NULL                 NULL

我设法让代码几乎可以做到这一点。

select distinct a.ssn, b.name, a.event, a.event_date, 
c.event as prior_event, c.event_date as prior_date
from history a
left join basic_data b
on b.ssn = a.ssn
Left Join
(select distinct c.ssn, c.event_date, c.event
from history c

 ) c
on c.ssn = a.ssn and (a.event > c.event)

order by a.ssn asc, a.event_date desc

这给了我这个 output:

Name            Event              Date of Event     Prior Event          Date of prior event
John Smith      Terminated         5/13/2017         Return from Leave     4/13/2017
John Smith      Terminated         5/13/2017         Paid Leave            3/31/2017
John Smith      Terminated         5/13/2017         Hire                  1/1/2000
John Smith      Return from Leave  4/13/2017         Paid Leave            3/31/2017
John Smith      Return from Leave  4/13/2017         Hire                  1/1/2000
John Smith      Paid Leave         3/31/2017         Hire                  1/1/2000
John Smith      Hire               1/1/2000          NULL                  NULL

它为该事件之前的每个事件显示多行,而不仅仅是它之前的一个。 如何摆脱所有额外的行?

您可以使用lead()分析 function order by event_date desc

select h.name as "Name", h.event as "Event", h.event_date as "Date of Event",
       lead(h.event) over (order by event_date desc) as "Prior Event",
       lead(h.event_date) over (order by event_date desc) as "Date of prior event"
  from history h
 order by event_date desc;

演示

如果您想要之前的事件,请使用lag() 此外,按员工划分非常重要:

select h.name, h.event, h.event_date,
       lag(h.event) over (partition by h.name order by h.event_date) as prior_event,
       lag(h.event_date) over (order by event_date) as prior_event-date
from history h
order by h.name, event_date desc;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM