new column for $ Change of unit price only from current period vs prior period)

时间:2018-03-09 19:18:58

标签: sql

Acct CODE      DESCRIPTION          UNIT   VOLUME SERVICE DATE     $ Change                
                                    PRICE         CHARGE       (Current vs prior 
                                                                      date
7    DDAIAMTH  RECOUPMENT MONTHLY   20     1       22     1/1/2018    
7    DDA15007  DESKTOP DEPOSIT CR   1.25   3       3.75   1/1/2018
7    DDADS510  ZERO BALANCE MASTER  30     1       30     1/1/2018
7    DDA22051  RECOUPMENT MONTHLY   22     1       20     2/1/2018
3    DDA22051  DESKTOP DEPOSIT      20     1       20     2/1/2018
3    DDA22051  ZERO BALANCE MASTER  20     1       20     2/1/2018

need a new column showing the difference of unit price only from current period (2-1-2018) vs prior period (1-1-2018) per description. example: (recoupment monthly on 2-1-2018 is $22 minus $20 (recoupment monthly on 2-1-2018) = 2 ($change amount) need a new column for the change amount..

1 个答案:

答案 0 :(得分:0)

SELECT a.*, a.UNITPRICE - 
(SELECT TOP 1 UNITPRICE FROM @Table b WHERE b.DATE < a.DATE) AS [$ CHANGE]
FROM @Table a

使用简单的子查询会有所帮助。可能不是很优化。但这会产生目标结果

+------+----------+---------------------+-----------+--------+---------------+-------------------------+----------+
| Acct |   CODE   |     DESCRIPTION     | UNITPRICE | VOLUME | SERVICECHARGE |          DATE           | $ CHANGE |
+------+----------+---------------------+-----------+--------+---------------+-------------------------+----------+
|    7 | DDAIAMTH | RECOUPMENT MONTHLY  |     20.00 |      1 |         22.00 | 2018-01-01 00:00:00.000 | NULL     |
|    7 | DDA15007 | DESKTOP DEPOSIT CR  |      1.25 |      3 |          3.75 | 2018-01-01 00:00:00.000 | NULL     |
|    7 | DDADS510 | ZERO BALANCE MASTER |     30.00 |      1 |         30.00 | 2018-01-01 00:00:00.000 | NULL     |
|    7 | DDA22051 | RECOUPMENT MONTHLY  |     22.00 |      1 |         20.00 | 2018-02-01 00:00:00.000 | 2.00     |
|    3 | DDA22051 | DESKTOP DEPOSIT     |     20.00 |      1 |         20.00 | 2018-02-01 00:00:00.000 | 0.00     |
|    3 | DDA22051 | ZERO BALANCE MASTER |     20.00 |      1 |         20.00 | 2018-02-01 00:00:00.000 | 0.00     |
+------+----------+---------------------+-----------+--------+---------------+-------------------------+----------+