I have a set of tables containing weeks, products, inventory and weekly forecasts, from which I want to choose an inventory of goods in week X and the latest forecasts. But I just can't figure out SQL:
create table products ( product_id integer ); create table inventory ( product_id integer, asof_week integer, qoh float8 ); create table forecast ( product_id integer, for_week integer, asof_week integer, projection float8 ); create table weeks ( wkno integer ); insert into weeks values (4),(5),(6),(7); insert into products values(1),(2); insert into inventory values(1,5,10),(1,6,20),(2,6,200); insert into forecast values(1,4,1,10),(1,4,2,11),(1,4,3,12),(1,4,4,13), (1,5,1,11),(1,5,2,11),(1,5,3,21),(1,5,4,31),
And request:
select p.product_id "product", i.asof_week "inven asof", i.qoh "qoh", f.for_week "fcast for", f.projection "fcast qty", f.asof_week "fcast asof" from weeks w, products p left join inventory i on(p.product_id = i.product_id) left join forecast f on(p.product_id = f.product_id) where (i.asof_week is null or i.asof_week = w.wkno) and (f.for_week is null or f.for_week = w.wkno) and (f.asof_week is null or f.asof_week = (select max(f2.asof_week) from forecast f2 where f2.product_id = f.product_id and f2.for_week = f.for_week)) order by p.product_id, i.asof_week, f.for_week, f.asof_week
For example, for weeks 4-7, I am looking for a set of results:
product week qoh projection 1 4 - 13 1 5 10 31 1 6 20 42 1 7 - 16 2 6 200 2000 2 7 - 2100
BUT in reality I get only 3 lines:
product | inven asof | qoh | fcast for | fcast qty | fcast asof ---------+------------+-----+-----------+-----------+------------ 1 | 5 | 10 | 5 | 31 | 4 1 | 6 | 20 | 6 | 42 | 6 2 | 6 | 200 | 6 | 2000 | 5 (3 rows) Time: 2.531 ms
I am new to SQL and can use some useful pointers.
Some data notes: I have several other data tables that I illustrated in this example to focus on this problem, at least one of them is similar in nature to a table of predicted values ββ(i.e. with several version lines for each product x week). There are about 100 forecast lines for each product X week, so somewhere I also have to worry about efficiency ... but first correct the results.
I'm on postgresql 9.2.
Thanks.