Using a variable period in an interval in Postgres

前端 未结 2 1933
再見小時候
再見小時候 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;
    
    0 讨论(0)
  • 2020-12-01 14:18

    Use this line:

    startDate TIMESTAMP := endDate - ($3 || ' MONTH')::INTERVAL;
    

    and note the space before MONTH. Basically: You construct a string with like 4 MONTH and cast it with ::type into a proper interval.

    Edit: I' have found another solution: You can calculate with interval like this:

    startDate TIMESTAMP := endDate - $3 * INTERVAL '1 MONTH';
    

    This looks a little bit nicer to me.

    0 讨论(0)
提交回复
热议问题