Oracle日期差异获得的年数

时间:2011-10-30 03:02:53

标签: oracle select

有没有办法计算日期之间的年数。不知道如何做到这一点,同时考虑到飞跃,什么不是。是否可以在SELECT中执行IF语句?

由于

5 个答案:

答案 0 :(得分:40)

我使用months_between,可能与floor结合使用:

select floor(months_between(date '2012-10-10', date '2011-10-10') /12) from dual;

select floor(months_between(date '2012-10-9' , date '2011-10-10') /12) from dual;

floor确保你得到圆满的岁月。如果你想要小数部分,你显然不想使用floor

答案 1 :(得分:15)

如果您只想要多年的差异,那就是:

SELECT EXTRACT(YEAR FROM date1) - EXTRACT(YEAR FROM date2) FROM mytable

或者你也想要分数年?

SELECT (date1 - date2) / 365.242199 FROM mytable
根据谷歌的说法,365.242199是1天。

答案 2 :(得分:2)

我必须实现一年的diff功能,其功能与 datediff类似。在这种情况下,计算实际年份差异,而不是四舍五入的日差。因此,如果有两个日期相隔一天,则年份差异可以为1(请参阅select datediff(year, '20141231', '20150101'))。

如果年份差异必须以这种方式计算,那么使用:

EXTRACT(YEAR FROM date_to) - EXTRACT(YEAR FROM date_from)

仅用于记录(几乎)完整的约会功能:

CREATE OR REPLACE FUNCTION datediff (datepart IN VARCHAR2, date_from IN DATE, date_to IN DATE)
RETURN NUMBER
AS
  diff NUMBER;
BEGIN
  diff :=  CASE datepart
    WHEN 'day'   THEN TRUNC(date_to,'DD') - TRUNC(date_from, 'DD')
    WHEN 'week'  THEN (TRUNC(date_to,'DAY') - TRUNC(date_from, 'DAY')) / 7
    WHEN 'month' THEN MONTHS_BETWEEN(TRUNC(date_to, 'MONTH'), TRUNC(date_from, 'MONTH'))
    WHEN 'year'  THEN EXTRACT(YEAR FROM date_to) - EXTRACT(YEAR FROM date_from)
  END;
  RETURN diff;
END;";

答案 3 :(得分:0)

如果一年的闰年为366天,则需要找到年份的差异。

我在oracle工作不多,请把它做得更好。 我是这样做的:

SELECT CASE
          WHEN    ( (fromisleapyear = 'Y') AND (frommonth < 3))
               OR ( (toisleapyear = 'Y') AND (tomonth > 2)) THEN
             datedif / 366
          ELSE
             datedif / 365
       END
          yeardifference
  FROM (SELECT datedif,
               frommonth,
               tomonth,
               CASE
                  WHEN (       (MOD (fromyear, 4) = 0)
                           AND (MOD (fromyear, 100) <> 0)
                        OR (MOD (fromyear, 400) = 0)) THEN
                     'Y'
               END
                  fromisleapyear,
               CASE
                  WHEN (   (MOD (toyear, 4) = 0) AND (MOD (toyear, 100) <> 0)
                        OR (MOD (toyear, 400) = 0)) THEN
                     'Y'
               END
                  toisleapyear
          FROM (SELECT (:todate - :fromdate) AS datedif,
                       TO_CHAR (:fromdate, 'YYYY') AS fromyear,
                       TO_CHAR (:fromdate, 'MM') AS frommonth,
                       TO_CHAR (:todate, 'YYYY') AS toyear,
                       TO_CHAR (:todate, 'MM') AS tomonth
                  FROM DUAL))

答案 4 :(得分:0)

对于Oracle SQL Developer,我可以使用下面的SQL行来计算年份之间的差异。这是为了获得相差0到10年的Year。您也可以像其他响应中所示的那样处理ifs。祝您编码愉快!

TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) > 0 and TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) < 10