使用Oracle PL/SQL查找历史记录

使用Oracle PL/SQL查找历史记录,sql,oracle,date,select,plsql,Sql,Oracle,Date,Select,Plsql,我有下面的Oracle员工表,它跟踪员工在不同部门之间的流动 EMPID DEPARTMENT RECORD_DATE 123456 Technology 2019-01-01 123456 Technology 2019-02-25 123456 Finance 2019-03-01 123456 Finance 2019-09-28 123456 HR 2020-03-01 987654 HR 2019-04-01

我有下面的Oracle员工表,它跟踪员工在不同部门之间的流动

EMPID   DEPARTMENT  RECORD_DATE
123456  Technology  2019-01-01
123456  Technology  2019-02-25
123456  Finance     2019-03-01
123456  Finance     2019-09-28
123456  HR          2020-03-01

987654  HR          2019-04-01
987654  Finance     2019-09-01
987654  HR          2020-01-31
我需要编写一个Oracle PL/SQL脚本,允许用户定义部门名称和历史日期,从而使查询显示在特定时间点分配给该部门的所有员工

示例:如果我想了解2019-10-01年在财务部门工作的所有员工,查询将返回:

EMPID   DEPARTMENT  DEPARTMENT_START_DATE  
123456  Finance     2019-03-01    
987654  Finance     2019-09-01 
请注意,部门休假日期会很好,但可以选择


有什么想法吗?

您可以使用窗口功能:

select empid, department, record_date
from (
    select 
        t.*, 
        lead(record_date) over(partition by empid order by record_date) lead_record_date
    from mytable t
) t
where 
    department = :department_id
    and :target_date >= record_date 
    and (:target_date < lead_record_date or lead_record_date is null)
:department\u id和:target\u date表示查询的参数


在子查询中,lead检索相同empid的下一个记录\ U日期。外部查询使用该信息作为筛选参数来定位相关记录。

在给定的示例中,您似乎需要每个部门(如果已工作)的带有历史日期的员工列表。这可以通过简单的子查询实现

select empid,record_date from(
select empid,department,record_Date,ROW_NUMBER() over (partition by empid,department order by empid) as id
from employee)a
where id=1
order by 3

为什么PL/SQL—简单的SQL SELECT语句还不够?提示:许多不知情的人认为PL/SQL意味着Oracle SQL。事实并非如此。