如何遍历表格直到达到条件

时间:2012-12-06 11:54:54

标签: sql-server-2005

我有一个表产品,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

1 个答案:

答案 0 :(得分: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 Location取决于Product和Location,因此它将是一个自己的表。我指出它是因为如果您的数据包含单个产品的不同Picked Quantities / ShortFall,那么上述查询将会中断;我提到的标准化表格无法实现这种情况。