我有一组表,其中包含周、产品、库存和每周预测,我想从中选择 X 周产品库存和最新预测。但我就是无法掌握 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),
--corr:one too many (1,6,1,10),(1,6,2,11),(1,6,3,12),(1,6,4,22),(1,6,5,32),(1,6,5,42),(1,6,6,42),
(1,6,1,10),(1,6,2,11),(1,6,3,12),(1,6,4,22),(1,6,5,42),(1,6,6,42),
(1,7,1,10),(1,7,6,16),
(2,6,5,2000),(2,7,5,2100),(2,8,5,30);
和一个查询:
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
例如,对于第 4-7 周,我正在寻找一个结果集:
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
但实际上我只得到 3 行:
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
我对 SQL 比较陌生,可以使用一些有用的指针。
关于数据的一些注释:我有几个其他数据表要加入,我在示例中省略了这些数据表,以专注于这个问题,其中至少一个在性质上与预测数量表相似(即,每个产品都有多个版本行x 周)。每个产品 X 周大约有 100 个预测行,所以在某个地方我还必须担心效率……但首先要正确结果。
我在 postgresql 9.2 上。
谢谢。