查找满足现有数量的前N个收据记录

时间:2013-05-07 19:26:55

标签: sql tsql

以下是特定部分的数据。 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

但这只会返回第一行。

由于

1 个答案:

答案 0 :(得分: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