Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's hard to give general pointers without knowing the rest of your data model, but I should say this: I generally find that queries are easier to reason about when I keep them as "flat" as possible. Also, as soon as I have a bunch of null checks, I either try to add guarantees to my data, or re-pivot my query around a different "root" table.</p> <p>Anyway, <a href="http://sqlfiddle.com/#!12/41a0e/13/0" rel="nofollow">the following</a> should work for you (although I can't guarantee that it will work for any data, especially in the presence of duplicates):</p> <pre><code>select products.product_id, weeks.wkno, inventory.qoh, max(projection) from forecast join products on products.product_id = forecast.product_id join weeks on weeks.wkno = forecast.for_week left join inventory on inventory.product_id = products.product_id and inventory.asof_week = weeks.wkno group by products.product_id, weeks.wkno, inventory.qoh </code></pre> <p>Sorry I can't give you that much advice. I hope this helps.</p> <p><strong>Edit</strong>: Tweaked the query to remove the cross join. Original version <a href="http://sqlfiddle.com/#!12/41a0e/12/0" rel="nofollow">here</a>. You might want a cross join if you wanted to left join forecasts if some were missing. For your specific example it's unneeded.</p> <p><strong>Edit 2</strong>: The above query is semantically incorrect. The <a href="http://sqlfiddle.com/#!12/e7f4d/4/0" rel="nofollow">following</a> is correct, but is not as illustrative of my point.</p> <pre><code>select p.product_id, p.wkno, p.qoh, f.projection from (select products.product_id, weeks.wkno, inventory.qoh, max(forecast.asof_week) max_p from forecast join products on products.product_id = forecast.product_id join weeks on weeks.wkno = forecast.for_week left join inventory on inventory.product_id = products.product_id and inventory.asof_week = weeks.wkno group by products.product_id, weeks.wkno, inventory.qoh) as p join forecast f on f.product_id = p.product_id and f.for_week = p.wkno and f.asof_week = p.max_p </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload