两个日期之间的月份功能

时间:2013-01-10 05:37:09

标签: function postgresql postgresql-9.1 postgresql-9.2

在oracle中我可以发现没有:使用MONTHS_BETWEEN函数之间的几个月。

在postgres中,我正在使用提取功能。 eg.like

select 
    extract(year from age(current_date, '2012-12-09')) * 12
    + 
    extract(month from age(current_date, '2012-12-09'))

postgres中还有其他方法(内置函数)吗?

4 个答案:

答案 0 :(得分:10)

这很容易在PostgreSQL中重新实现,只需使用SQL函数来整理你已经拥有的东西:

create function months_of(interval)
 returns int strict immutable language sql as $$
  select extract(years from $1)::int * 12 + extract(month from $1)::int
$$;

create function months_between(date, date)
 returns int strict immutable language sql as $$
   select abs(months_of(age($1, $2)))
$$;

现在select months_between('1978-06-20', '2011-12-09')生成401。

答案 1 :(得分:3)

不幸的是,似乎没有,因为extract(month ...)会返回 modulo 12 的月数。

你可以做一个简单的简化;删除age()的第一个参数 - 默认值为current_date的年龄,因此这两个参数相同:

age(current_date, '2012-12-09')
age('2012-12-09')

答案 2 :(得分:1)

您可以使用UDF,例如我找到了以下here

   CREATE OR REPLACE FUNCTION DateDiff (units VARCHAR(30), start_t TIMESTAMP, end_t TIMESTAMP) 
     RETURNS INT AS $$
   DECLARE
     diff_interval INTERVAL; 
     diff INT = 0;
     years_diff INT = 0;
   BEGIN
     IF units IN ('yy', 'yyyy', 'year', 'mm', 'm', 'month') THEN
       years_diff = DATE_PART('year', end_t) - DATE_PART('year', start_t);

       IF units IN ('yy', 'yyyy', 'year') THEN
         -- SQL Server does not count full years passed (only difference between year parts)
         RETURN years_diff;
       ELSE
         -- If end month is less than start month it will subtracted
         RETURN years_diff * 12 + (DATE_PART('month', end_t) - DATE_PART('month', start_t)); 
       END IF;
     END IF;

     -- Minus operator returns interval 'DDD days HH:MI:SS'  
     diff_interval = end_t - start_t;

     diff = diff + DATE_PART('day', diff_interval);

     IF units IN ('wk', 'ww', 'week') THEN
       diff = diff/7;
       RETURN diff;
     END IF;

     IF units IN ('dd', 'd', 'day') THEN
       RETURN diff;
     END IF;

     diff = diff * 24 + DATE_PART('hour', diff_interval); 

     IF units IN ('hh', 'hour') THEN
        RETURN diff;
     END IF;

     diff = diff * 60 + DATE_PART('minute', diff_interval);

     IF units IN ('mi', 'n', 'minute') THEN
        RETURN diff;
     END IF;

     diff = diff * 60 + DATE_PART('second', diff_interval);

     RETURN diff;
   END;
   $$ LANGUAGE plpgsql;

答案 3 :(得分:0)

SELECT date_part ('year', f) * 12
      + date_part ('month', f)
FROM age (CURRENT_DATE, '2014-12-01') f