使用“运行总计”来限制所选行

时间:2015-09-24 19:55:19

标签: sql selection running-total

当我的运行总数达到5000时,我需要停止选择记录。以下是我的查询确实产生了所需的运行总计。是否有可能以我想要的方式使用这个总数?感谢。

WITH CTE AS (
    SELECT sddoco AS DocNo, sduorg as OrdQty, sdlitm AS EAN

FROM [QADTA].[f4211]

WHERE sdmcu = '        1070'
    )
SELECT DocNo, OrdQty, EAN
   ,SUM(OrdQty) OVER (ORDER BY DocNo ROWS UNBOUNDED PRECEDING) AS CumulativeQty
   ,SUM(OrdQty) OVER (ORDER BY DocNo RANGE UNBOUNDED PRECEDING) AS CumulativeSumByRange

FROM CTE

ORDER BY DocNo, EAN

我希望能够添加CumulativeQty< = 5000的位置,所以我只选择了记录,直到总数达到5000.

1 个答案:

答案 0 :(得分:1)

使用子查询:

with . . .
SELECT t.*
FROM (SELECT DocNo, OrdQty, EAN,
             SUM(OrdQty) OVER (ORDER BY DocNo ROWS UNBOUNDED PRECEDING) AS CumulativeQty
             SUM(OrdQty) OVER (ORDER BY DocNo RANGE UNBOUNDED PRECEDING) AS CumulativeSumByRange
      FROM CTE
     ) t
WHERE t.CumulativeQty <= 5000
ORDER BY DocNo, EAN;