我需要一些关于窗口函数的帮助.
我最近一直在玩sql 2012窗口函数.我知道您可以计算窗口内的总和以及窗口内的运行总和.但我很想知道; 是否有可能计算以前的运行总量,即不包括当前行的运行总量?我假设您需要使用ROW或RANGE参数,我知道有一个CURRENT ROW选项,但我需要一个CURRENT ROW - 我的语法无效.我对ROW和RANGE参数的了解是有限的,所以任何帮助都会感激不尽.
我知道这个问题有很多解决方案,但我希望了解ROW,RANGE参数,我认为这些问题可以解决.我已经包含了一种可能的方法来计算之前的运行总量,但我想知道是否有更好的方法.
USE AdventureWorks2012 SELECT s.SalesOrderID , s.SalesOrderDetailID , s.OrderQty , SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID) AS RunningTotal , SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID ORDER BY SalesOrderDetailID) - s.OrderQty AS PreviousRunningTotal -- Sudo code - I know this does not work --, SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID -- ORDER BY SalesOrderDetailID -- ROWS BETWEEN UNBOUNDED PRECEDING -- AND CURRENT ROW - 1) -- AS SudoCodePreviousRunningTotal FROM Sales.SalesOrderDetail s WHERE SalesOrderID IN (43670, 43669, 43667, 43663) ORDER BY s.SalesOrderID , s.SalesOrderDetailID , s.OrderQty提前致谢
1> Andomar..:您可以减去当前行的值:
SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID ORDER BY SalesOrderDetailID) - s.OrderQty或者根据MSDN和ypercube的答案的语法:
::= { UNBOUNDED PRECEDING | PRECEDING | CURRENT ROW } - >
SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID ORDER BY SalesOrderDetailID ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)