Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is a variation of the <code>greatest-n-per-group</code> problem that comes up frequently.</p> <p>You want the single row form FinishTierPrice (call it <code>p1</code>), matching the FinishOption and with the greatest Qty, but still less than or equal to the Qty of the ProductOptionTier.</p> <p>One way to do this is to try to match a second row (<code>p2</code>) from FinishTierPrice that would have the same FinishOption and a greater Qty. If no such row exists (use an outer join and test that it's NULL), then the row found by <code>p1</code> is the greatest.</p> <pre><code>SELECT Product.Name, ProductOption.Name, a.Qty, a.Price, SheetSize.UpgradeCost, FinishType.Name, FinishOption.Name, FinishTierPrice.Qty, FinishTierPrice.Price FROM `Product` JOIN `ProductOption` ON Product.idProduct = ProductOption.Product_idProduct JOIN `ProductOptionTier` AS a ON a.ProductOption_idProductOption = ProductOption.idProductOption JOIN `PaperSize` ON PaperSize.idPaperSize = ProductOption.PaperSize_idPaperSize JOIN `SheetSize` ON SheetSize.PaperSize_idPaperSize = PaperSize.idPaperSize JOIN `FinishOption` ON FinishOption.Product_idProduct = Product.idProduct JOIN `FinishType` ON FinishType.idFinishType = FinishOption.Finishtype_idFinishType JOIN `FinishTierPrice` AS p1 ON p1.FinishOption_idFinishOption = FinishOption.idFinishOption AND p1.Qty &lt;= a.Qty LEFT OUTER JOIN `FinishTierPrice` AS p2 ON p2.FinishOption_idFinishOption = FinishOption.idFinishOption AND p2.Qty &lt;= a.Qty AND (p2.Qty &gt; p1.Qty OR p2.Qty = p1.Qty AND p2.idFinishTierPrice &gt; p1.idFinishTierPrice) WHERE Product.idProduct = 1 AND p2.idFinishTierPrice IS NULL </code></pre>
    singulars
    1. This table or related slice is empty.
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    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