I have a query which calculate latest price till last month. I need to schedule it every month so i can get latest price till last month. If current month is march, it will calculate latest price till Febuary. If current month is april it should calculate till march.
Here is my query:-
SELECT
item,
cost_price,
effective_date
FROM
join_purchase_table
WHERE effective_date BETWEEN '2023-02-01' AND '2023-02-28'
UNION
(
SELECT
item,
cost_price,
effective_date
FROM (
SELECT
item,
cost_price,
effective_date,
row_number() over(partition by item order by effective_date desc) AS rn
FROM
join_purchase_table
WHERE
effective_date<'2023-03-01'
Here i have enter date statically, How can i change date dynamically which will calculate latest price till last month and it run every month?
2
Answers
To make it dynamic when you run in the month following the one you are interested in.
Though as noted in the comments this query is not complete. This answer just covers how to create the dynamic dates.
The following query gets the most recent cost_price for each item for the previous month:
PostgreSQL doesn’t have an internal mechanism for scheduling recurrent queries; however, this can be accomplished using external mechanisms such as cron or pg_cron.