My forecast table stores the current week, and then forecasted amounts for 26 weeks out:
CREATE TABLE forecast_listings (
product integer NOT NULL
, current_week_date date
, weekplus0 integer NOT NULL DEFAULT 0
, weekplus1 integer NOT NULL DEFAULT 0
, weekplus2 integer NOT NULL DEFAULT 0
, weekplus3 integer NOT NULL DEFAULT 0
, weekplus4 integer NOT NULL DEFAULT 0
-- etc
, weekplus24 integer NOT NULL DEFAULT 0
, weekplus25 integer NOT NULL DEFAULT 0
);
For example forecasting a single item, I select a single row with the most recent current_week_date
and then look at relative weeks.
SELECT
unnest(
array[
to_char(week_current_date, 'YYYY-MM-DD'),
to_char(week_current_date + interval '1 weeks', 'YYYY-MM-DD'),
to_char(week_current_date + interval '2 weeks', 'YYYY-MM-DD'),
to_char(week_current_date + interval '3 weeks', 'YYYY-MM-DD'),
to_char(week_current_date + interval '4 weeks', 'YYYY-MM-DD')
-- ...all the way to 25
]
) AS "Week",
unnest(
array[
weekplus0,
weekplus1,
weekplus2,
weekplus3,
weekplus4
-- ...all the way to 25
]
) AS "Count"
FROM (
SELECT * FROM forecast_listings
WHERE product_id = 1
ORDER BY week_current_date DESC
LIMIT 1
) as row
I would like to do this with Postgres, essentially fetching a row and transposing each weeks number to a row with a date column and count column:
week, count
2017-10-01,100
2017-10-08,200
2017-10-15,150
etc.