Calculation in Sql Server

前端 未结 6 677
孤街浪徒
孤街浪徒 2021-01-31 02:21

I trying to perform following calculation

Sample data:

CREATE TABLE #Table1
  (
     rno   int identity(1,1),
     ccp   varchar(50),
          


        
6条回答
  •  既然无缘
    2021-01-31 03:22

    After playing with it for some time I believe the answer to the bounty question of whether or not this can be done with a sum() over (order by) is NO. This code is as close as I could get:

    select  *, col3 - sum(col1 * power(1 + col4, row_num)) over (partition by ccp order by col1)
    from    (
            select  *, row_number() over (partition by ccp order by rno asc) row_num
            from    @Table1
            ) a
    order   by 1,2;
    

    This will return correct results for the first row in each ccp group. By calculating row_num using rno desc instead then the final row in each ccp will be correct.

    It appears that the only ways to get this to work in the simple way that the syntax suggests would be:

    1. Syntax support to reference the actual row within the aggregate over function. This does exist in T-SQL as far as I can find.
    2. Syntax support for a window function within a window function. This also is not permitted in T-SQL per the following error:

    Windowed functions cannot be used in the context of another windowed function or aggregate.

    This was an interesting problem. I'd be curious how this solution performs against your large dataset even though the actual result is incorrect.

提交回复
热议问题