在隔离的行上运行Delta值 - SQL Server 2008

时间:2016-09-20 07:48:49

标签: sql-server sum delta

我的下表包含Position_Date,Deal_Nr和Market Value列。 现在我想创建第四列,计算每笔交易2天之间的市场价值增量。 例如,交易nr 100,MV 14/9 = 500. MV 13/9 = 600. 500-600 = -100 ......

如果我对头寸日期求和并进行分组,我知道如何做到这一点,但是有没有办法计算每笔交易上孤立的delta,而不是将case_nr作为条件?我有100个不同的deal_nr和新的交易将来,所以我希望查询是静态的。

      Position_date |Deal_Nr|   Market Value    |   Delta Market Value
        2016-09-14  |   100 |   500             |   -100
        2016-09-14  |   101 |   1000            |   200
        2016-09-14  |   102 |   120             |   -30
        2016-09-14  |   103 |   400             |   -40
        2016-09-13  |   100 |   600             |   -300
        2016-09-13  |   101 |   800             |   100
        2016-09-13  |   102 |   150             |   -150
        2016-09-13  |   103 |   440             |   240
        2016-09-12  |   100 |   900             |   N/A
        2016-09-12  |   101 |   700             |   N/A
        2016-09-12  |   102 |   300             |   N/A
        2016-09-12  |   103 |   200             |   N/A

如果我要计算聚合的增量,按位置日期分组,以下工作。

          Select  
        Position_date,
        Market_Value,
        Delta_MV = sum(Market_value) - (select sum(Market_value) from t1 
                                       where position_Date = a.position_date -1 
                                       Group by position_date)

        from t1 as a
        Group by position_date   

1 个答案:

答案 0 :(得分:1)

您应该使用LEFT JOIN,如下所示:

    DECLARE @Tbl TABLE (Position_date DATETIME, MarketValue INT,  Deal_Nr INT)
INSERT INTO @Tbl
VALUES 
('2016-09-14', 500 ,100  ),
('2016-09-14', 1000,101  ),
('2016-09-14', 120 ,102  ),
('2016-09-14', 400 ,103  ),
('2016-09-13', 600 ,100  ),
('2016-09-13', 800 ,101  ),
('2016-09-13', 150 ,102  ),
('2016-09-13', 440 ,103  ),
('2016-09-12', 900 ,100   ),
('2016-09-12', 700 ,101   ),
('2016-09-12', 300 ,102   ),
('2016-09-12', 200 ,103   )

SELECT
    A.Position_date,
    A.MarketValue,
    A.MarketValue - B.MarketValue AS DeltaMarketValue       
FROM
    @Tbl A LEFT JOIN 
    @Tbl B ON A.Deal_Nr = B.Deal_Nr AND 
              A.Position_date <> B.Position_date AND
              DATEADD(DAY, -1, A.Position_date) = B.Position_date

结果:

Position_date   MarketValue DeltaMarketValue
--------------- ----------- ----------------
2016-09-14          500         -100
2016-09-14          1000        200
2016-09-14          120         -30
2016-09-14          400         -40
2016-09-13          600         -300
2016-09-13          800         100
2016-09-13          150         -150
2016-09-13          440         240
2016-09-12          900         NULL
2016-09-12          700         NULL
2016-09-12          300         NULL
2016-09-12          200         NULL