如何在pgsql中按月获取日期。我需要按日期的月份范围划分一个值。如 2016/01/31 和 2016/03/31 有 2个月期间,我需要将值除以2 即可。我发送两个日期作为pgSQL存储过程的参数。
答案 0 :(得分:1)
这是按月份的功能日期周期返回整数
CREATE OR REPLACE FUNCTION date_period(start_date varchar,end_date varchar) RETURNS integer AS $LABEL$
DECLARE
v_result integer;
BEGIN
select into v_result date_part('months',end_date::date)- date_part('months',start_date::date) as date_period;
/* v_result is integer */
RETURN (v_result);
/* COMMENTS THIS IF YOU IN DEBUG MODE */
EXCEPTION WHEN OTHERS THEN RETURN (999);
END;
$LABEL$ LANGUAGE plpgsql
SECURITY DEFINER;
不同年份,您可以使用此功能
CREATE OR REPLACE FUNCTION date_period(start_date varchar,end_date varchar) RETURNS integer AS $LABEL$
DECLARE
v_result integer;
BEGIN
select into v_result ((extract( epoch from end_date::date)-extract( epoch from start_date::date))/60/60/24/30)::integer as date_period;
/* v_result is integer */
RETURN (v_result);
/* COMMENTS THIS IF YOU IN DEBUG MODE */
EXCEPTION WHEN OTHERS THEN RETURN (999);
END;
$LABEL$ LANGUAGE plpgsql
SECURITY DEFINER;
EXEC:SELECT * FROM date_period('2016/01/31','2017/03/31');