计算两个日期之间的月份

dat*_*ili 5 oracle

对于大学课程,我被赋予了以下任务

假设我们有employee一张像(first_name, last_name, salary, hire_date, ...). 有规定规定,每位员工在入职后每年都必须与公司续签合同。显示每位员工下一次续约前还有多少个月。

这是我的尝试:

select (abs(months_between(sysdate,hire_date)/12 - 
         round((months_between(sysdate,e.hire_date))/12)))
from employees e
Run Code Online (Sandbox Code Playgroud)

Jac*_*las 7

如果您的员工表很大,有更有效的方法可以做到这一点,但这是我觉得最容易理解的方式:)

试验台:

create table employee( employee_id integer primary key, 
                       name varchar(100) not null, 
                       hire_date date not null );

insert into employee(employee_id, name, hire_date)
values(1, 'Alice', to_date('20090909', 'YYYYMMDD'));

insert into employee(employee_id, name, hire_date)
values(2, 'Bob', to_date('20101010', 'YYYYMMDD'));

insert into employee(employee_id, name, hire_date)
values(3, 'Chris', to_date('20111111', 'YYYYMMDD'));

insert into employee(employee_id, name, hire_date)
values(4, 'David', to_date('20101231', 'YYYYMMDD'));
Run Code Online (Sandbox Code Playgroud)

询问:

with w as ( select e.*, ( select max(add_months(hire_date, 12*level))
                          from dual
                          connect by add_months(hire_date, 12*(level-1))<sysdate )
                      as next_anniversary
            from employee e )
select w.*, round(months_between(next_anniversary, sysdate)) as months_from_now from w;
Run Code Online (Sandbox Code Playgroud)

结果:

EMPLOYEE_ID            NAME       HIRE_DATE                 NEXT_ANNIVERSARY          MONTHS_FROM_NOW
---------------------- ---------- ------------------------- ------------------------- ----------------------
1                      Alice      09-SEP-09 00.00.00        09-SEP-12 00.00.00        10                     
2                      Bob        10-OCT-10 00.00.00        10-OCT-12 00.00.00        11                     
3                      Chris      11-NOV-11 00.00.00        11-NOV-12 00.00.00        12                     
4                      David      31-DEC-10 00.00.00        31-DEC-11 00.00.00        1                      
Run Code Online (Sandbox Code Playgroud)

你可能喜欢floorceilround