我需要一些有关开窗功能的帮助。

我最近一直在使用sql 2012窗口功能。我知道您可以计算一个窗口内的总和和一个窗口内的运行总和。但是我在想;是否可以计算先前的运行总计,即不包括当前行的运行总计?我假设您需要使用ROW或RANGE参数,并且我知道有CURRENT ROW选项,但是我需要CURRENT ROW-I,这是无效的语法。我对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

提前致谢

最佳答案

您可以减去当前行的值:

SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID
                      ORDER BY SalesOrderDetailID) - s.OrderQty

或根据syntax at MSDNypercube's answer:
<window frame preceding> ::=
{
    UNBOUNDED PRECEDING
  | <unsigned_value_specification> PRECEDING
  | CURRENT ROW
}

->
SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID
                      ORDER BY SalesOrderDetailID
                      ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)

关于SQL Server 2012 Windowing函数计算运行总计,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16735292/

10-12 14:37