請注意,最好不要考慮SQL「循環訪問表」,而應考慮將其視爲對錶中某些行的子集進行操作。
它聽起來像你需要做的是創建一個運行總數,告訴你有多少物品,如果你從一個位置和所有位置在當前位置之前,然後檢查一下,看看是否會給你足夠的項目來彌補虧空。
根據您的示例數據,以下查詢可以工作,但如果位置實際上不是數字,那麼您需要添加行號列並稍微調整查詢以使用行號而不是位置號碼;它仍然與下面的查詢非常相似。
SELECT
Totals.Product, Totals.PickedQty, Totals.ShortFall, Totals.Location, Totals.LocationQty
FROM (
SELECT
TheTable.Product, TheTable.PickedQty, TheTable.ShortFall,
TheTable.Location, TheTable.LocationQty, SUM(ForRunningTotal.LocationQty) AS RunningTotal
FROM TheTable
JOIN TheTable ForRunningTotal ON TheTable.Product = ForRunningTotal.Product
AND TheTable.Location >= ForRunningTotal.Location
GROUP BY TheTable.Product, TheTable.PickedQty, TheTable.ShortFall, TheTable.Location, TheTable.LocationQty
) Totals
-- Note you could also change the join above so the running total is actually the count of only the rows above,
-- not including the current row; Then the WHERE clause below could be "Totals.RunningTotal < Totals.ShortFall".
-- I liked RunningTotal as the sum of this row and all prior, it seems more appropriate to me.
WHERE Totals.RunningTotal - Totals.LocationQty <= Totals.ShortFall
AND Totals.LocationQty > 0
而且 - 只要你在讀我的答案,一個不相關的邊注:根據你的數據顯示上方,數據庫模式是不是隻要是可以標準化。看起來Picked Quantity和ShortFall實際上只依賴於Product,因此它將成爲它自己的表格,然後Location數量取決於Product和Location,因此這將成爲它自己的表格。我指出,因爲如果您的數據包含單個產品的Picked Quantity/ShortFall不同,那麼上述查詢將會中斷;在我提到的標準化表格中,這種情況是不可能的。