週 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に慣れていないので、いくつかの便利なポインターを使用できます。
データに関するいくつかの注意事項: この問題に集中するために例から省略した他のいくつかのデータ テーブルを結合する必要があります。そのうちの少なくとも 1 つは、予測数量テーブルと性質が似ています (つまり、すべての製品に複数のバージョンの行があります)。 x 週間)。製品X週ごとに約100行の予測行があるため、どこかで効率についても心配する必要があります...しかし、最初に結果を修正してください。
私はpostgresql 9.2を使用しています。
ありがとう。