SQL: use WHERE clause in OVER()?

前端 未结 2 2250
轮回少年
轮回少年 2021-02-19 16:25

How can I use WHERE clause to filter in the OVER clause?

i.e. from the following data

LoanID | Principal | Tenor | Amortizin         


        
2条回答
  •  遥遥无期
    2021-02-19 17:07

    For the sample posted, it doesn't look like a filter is needed:

    SELECT LoanID, Principal, Tenor, AmortizingPrincipal
          ,SUM(AmortizingPrincipal) OVER(PARTITION BY LoanID ORDER BY Tenor Desc) AS BalancePrincipal
      FROM loan
      ORDER BY LoanID, Principal, Tenor
    

    UPDATE:

    Seems Sql Server 2008 does not have the windowing clause? I didn't even think you could create an analytic function without a windowing clause. The above sql was run on Oracle and Postgres without issue. By default the window clause is UNBOUNDED PRECEDING AND CURRENT ROW (from - to). But you could change the order and go from CURRENT ROW to UNBOUNDED FOLLOWING.

    UPDATE2:

    So I puzzled: what meaning would a (cumulative) SUM have in an analytic function if you are unable to order the rows within the partition? Is there an implicit ordering? I can change the window (below) and get the same result, but must provide the ORDER BY (in Oracle and Postgres). I can't see how the analytic SUM would have any meaning without the ORDER BY.

    SELECT LoanID, Principal, Tenor, AmortizingPrincipal
          ,SUM(AmortizingPrincipal) OVER(PARTITION BY LoanID ORDER BY tenor
                                         RANGE BETWEEN CURRENT ROW
                                           AND UNBOUNDED FOLLOWING) AS BalancePrincipal
      FROM loan
      ORDER BY LoanID, Principal, Tenor
    

提交回复
热议问题