1

以下是特定部分的数据。此示例中所有记录的OnHand数量相同,因为该示例仅针对一个部分。

OnHand     DateReceived    QuantityReceived     
24         2013-04-17           20
24         2013-04-01           12
24         2013-03-10           12
24         2013-03-01           12

我需要从收到的那部分采购订单中找到与手头数量相加的行。所以,在上面的例子中,我应该得到前 2 条记录,因为手头的数量是 24,而这个数量是由 20 件的收货和 12 件的收货来计算的。

我怎样才能做到这一点?

我尝试通过运行总数限制我的结果:

where (select SUM(QuantityReceived) from table t where t.ReceivedDate >= table.ReceivedDate)<=table.OnHand

但这只会返回第一行。

谢谢

4

1 回答 1

1

在 SQL Server 2012 中:

SELECT  *
FROM    (
        SELECT  *,
                SUM(quantityReceived) OVER (ORDER BY dateReceived DESC) psum
        FROM    mytable
        ) q
WHERE   onHand > psum - quantityReceived

在早期版本中:

SELECT  *
FROM    mytable m
WHERE   onhand >
        (
        SELECT  SUM(quantityReceived)
        FROM    mytable mi
        WHERE   mi.dateReceived >= m.dateReceived
        ) - quantityReceived
于 2013-05-07T19:41:58.010 回答