Using a variable period in an interval in Postgres

前端 未结 2 1935
再見小時候
再見小時候 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: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.

提交回复
热议问题