SUM直到按列排序的值

时间:2012-12-11 19:11:19

标签: sql sql-server tsql

我有一张包含产品,数量和重量的表格。我需要找到达到一定值的较重的产品。例如:

表:

Product     Qty Weight
PEN         100 50
PEN          10 30
PEN          80 20
PEN         250 20
PEN        1000 10
PAPER       150 80
PAPER      1500 20

查询:查找按重量排序达到最大200数量的PEN。

结果:

PEN         100 50
PEN          10 30
PEN          80 20

修改 结果是因为:100 + 10 + 80< 200。

1 个答案:

答案 0 :(得分:5)

如果您使用的是SQL 2012,则可以将这种方法用于运行总计:

Select
  Qty,
  Weight
From (
  Select
    Qty,
    Weight,
    Sum(Qty) Over(Order By Weight Desc Rows Between Unbounded Preceding And Current Row) As RunningQty
  From
    Test
  Where
    Product = 'PEN'
  ) a
Where
   RunningQty <= 200

http://sqlfiddle.com/#!6/6157b/4