Calculation in Sql Server

前端 未结 6 674
孤街浪徒
孤街浪徒 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:20

    Finally I achieved the result using below approach

    SELECT a.*,
           col3 - res AS Result
    FROM   #TABLE1 a
           CROSS apply (SELECT Sum(b.col1 * Power(( 1 + b.COL2 / 100.00 ), new_rn)) AS res
                        FROM   (SELECT Row_number()
                                         OVER(
                                           partition BY ccp
                                           ORDER BY rno DESC) new_rn,*
                                FROM   #TABLE1 b
                                WHERE  a.ccp = b.ccp
                                       AND a.rno >= b.rno)b) cs
    

    Result :

    +-----+------+------+------+------+----------+-------------+
    | rno | ccp  | col1 | col2 | col3 |   col4   |   Result    |
    +-----+------+------+------+------+----------+-------------+
    |   1 | ccp1 |   15 |   10 | 1100 | 0.100000 | 1083.500000 |
    |   2 | ccp1 |   20 |   10 | 1210 | 0.100000 | 1169.850000 |
    |   3 | ccp1 |   30 |   10 | 1331 | 0.100000 | 1253.835000 |
    |   4 | ccp2 |   10 |   15 |  900 | 0.150000 | 888.500000  |
    |   5 | ccp2 |   15 |   15 | 1000 | 0.150000 | 969.525000  |
    |   6 | ccp2 |   20 |   15 | 1010 | 0.150000 | 951.953750  |
    +-----+------+------+------+------+----------+-------------+
    

提交回复
热议问题