Using a variable period in an interval in Postgres

前端 未结 2 1934
再見小時候
再見小時候 2020-12-01 13:57

I have a relation that maintains monthly historical data. This data is added to the table on the last day of each month. A service I am writing can then be called specifying

2条回答
  •  佛祖请我去吃肉
    2020-12-01 14:15

    This code has nothing directly to do with your situation, but it does illustrate how to use variables in INTERVAL arithmetic. My table's name is "calendar".

    CREATE OR REPLACE FUNCTION test_param(num_months integer)
      RETURNS SETOF calendar AS
    $BODY$
    
        select * from calendar
        where cal_date <= '2008-12-31 00:00:00'
        and cal_date > date '2008-12-31' - ($1 || ' month')::interval;
    
    $BODY$
      LANGUAGE sql VOLATILE
      COST 100
      ROWS 1000;
    

提交回复
热议问题