7

For getting current date i use this..

select extract(year from sysdate) from dual;

For getting the date that my database hold i use this..

select extract(year from startdate) from staff;

But now i am trying to update a field call serviceYears inside staff, by using

current year - year of start date

to get the amount of years the staff have committed to work. how do i achieve it..

i am using oracle sql

Thanks!

I tried to use

SQL> select dual.sysdate-staff.startdatefrom dual,staff;

select dual.sysdate-staff.startdatefrom from dual,staff
            *
ERROR at line 1:
ORA-01747: invalid user.table.column, table.column, or column specification

I also tried

select SYSDATE-to_date('01-jan-2007','dd-mon-yyyy') from dual;

But it return me
SYSDATE-TO_DATE('01-JAN-2007','DD-MON-YYYY')
--------------------------------------------
                                  2136.93719

How do i just get the year?

4

5 回答 5

10

你可以这样做

UPDATE STAFF
SET serviceYear = ROUND((sysdate - startDate)/365)

前任:

select ROUND((sysdate - to_date('01-JAN-2007','DD-MON-YYYY'))/365) 
from dual; -- returns 6


select ROUND((sysdate - to_date('01-JAN-2005','DD-MON-YYYY'))/365,2) 
from dual; -- returns 7.85

更新:

SELECT 
FLOOR((SYSDATE - TO_DATE('01-JAN-2005','DD-MON-YYYY'))/365) YEARDOWN,
CEIL((SYSDATE - TO_DATE('01-JAN-2005','DD-MON-YYYY'))/365) YearUP
FROM DUAL;
于 2012-11-06T14:30:58.913 回答
1

你不需要 dual.sysdate - 你可以参考 sysdate。

select sysdate-staff.startdatefrom from staff
于 2012-11-06T14:29:21.800 回答
1

我认为FLOOR和的组合可能会更好地为您服务MONTHS_BETWEEN

SQL> CREATE TABLE t (start_date DATE);

Table created.

SQL> INSERT INTO t VALUES (TO_DATE('20070930','YYYYMMDD'));

1 row created.

SQL> SELECT FLOOR(MONTHS_BETWEEN(TRUNC(SYSDATE), start_date)/12) yrs_between_start_dt_and_today FROM t
  2  ;

YRS_BETWEEN_START_DT_AND_TODAY
------------------------------
                             5

SQL>

您可以根据需要调整舍入。此外,与除以硬编码 365 相比,此解决方案在闰年等方面表现更好。

于 2012-11-06T15:54:24.830 回答
0

如果您可以以月为单位进行衡量,请尝试使用months_between 函数:

http://www.techonthenet.com/oracle/functions/months_between.php

http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions094.htm#i78039

可以把它除以 12 得到年份。

于 2012-11-06T14:42:51.960 回答
-1
    SELECT extract(year from sysdate)-extract(year from TDATE) 
      FROM R_M 
CONNECT BY LEVEL <=1
于 2016-04-13T09:07:55.060 回答