1

我有一个表产品,pick_qty,shortfall,location,loc_qty

Product Picked Qty Shortfall  Location    Location Qty
1742        4       58           1              15
1742        4       58           2              20
1742        4       58           3              15
1742        4       58           4              20
1742        4       58           5              20
1742        4       58           6              20
1742        4       58           7              15
1742        4       58           8              15
1742        4       58           9              15
1742        4       58           10             20

我想要一个报告循环显示我需要减少的位置数量和数量,以弥补补货的不足。所以报告看起来像这样。

Product Picked Qty  Shortfall  Location  Location Qty
1742        4          58           1       15
1742        4          58           2       20
1742        4          58           3       15
1742        4          58           4       20
4

1 回答 1

0

请注意,最好不要将 SQL 视为“循环遍历表”,而应将其视为对表中某些行的子集进行操作。

听起来您需要做的是创建一个运行总计,告诉您如果从一个位置以及当前位置之前的所有位置取出所有物品,您将拥有多少物品,然后检查以查看如果这会给你足够的物品来弥补短缺。

根据您的示例数据,以下查询将起作用,但如果 Locations 实际上不是数字,那么您需要添加行号列并稍微调整查询以使用行号而不是位置号;它仍然与下面的查询非常相似。

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 Quantity 取决于 Product 和 Location,所以这将是一个自己的表。我指出这一点是因为如果您的数据包含单个产品的不同 Picked Quantities/ShortFall,那么上述查询将中断;对于我提到的规范化表,这种情况是不可能的。

于 2012-12-06T12:52:48.997 回答