在group by子句上运行日期之间的总和

时间:2016-09-09 09:36:02

标签: sql sql-server sql-server-2008 sum between

我有以下查询显示前3列:

select
    'Position Date' = todaypositiondate,
    'Realized LtD SEK' = round(sum(realizedccy * spotsek), 0),
     'Delta Realized SEK' = round(sum(realizedccy * spotsek) -  
                                (SELECT sum(realizedccy*spotsek) 
                                 FROM t1
                                 WHERE todaypositiondate = a.todaypositiondate - 1
                                 GROUP BY todaypositiondate), 0)
FROM 
    t1 AS a
GROUP BY 
    todaypositiondate
ORDER BY 
    todaypositiondate DESC

表:

Date        |   Realized    |   Delta   |   5 day avg delta
-------------------------------------------------------------------
2016-09-08  |   696 981 323 |    90 526 |      336 611
2016-09-07  |   696 890 797 |   833 731 |      335 232
2016-09-06  |   696 057 066 |    85 576 |      84 467
2016-09-05  |   695 971 490 |    86 390 |      83 086
2016-09-04  |   695 885 100 |    81 434 |      80 849
2016-09-03  |   695 803 666 |    81 434 |      78 806
2016-09-02  |   695 722 231 |    79 679 |      74 500
2016-09-01  |   695 642 553 |    75 305 |   
2016-08-31  |   695 567 248 |    68 515 |   

如何创建实现delta的5d平均值?

基于delta,我尝试了以下操作,但它不起作用:

select
    todaypositiondate,
    '30d avg delta' = (select sum(realizedccy * spotsek)
                       from T1
                       where todaypositiondate between a.todaypositiondate and a.todaypositiondate -5
                       group by todaypositiondate)
from 
    T1 as a
group by 
    todaypositiondate
order by 
    todaypositiondate desc

2 个答案:

答案 0 :(得分:1)

不要对列名使用单引号。仅对字符串和日期文字使用单引号。

我会把它写成:

with t as (
      select todaypositiondate as PositionDate,
             round(sum(realizedccy * spotsek), 0) as RealizedSEK,
      from t1 a
      group by todaypositiondate
)
select a.*,
       (a.RealizedSEK - a_prev.RealizedSEK) as diff_1,
       (a.RealizedSEK - a_prev5.RealizedSEK)/5 as avg_diff_5
from a outer apply
     (select top 1 a_prev.*
      from a a_prev
      where a_prev = a.PositionDate - 1
     ) a_prev outer apply
     (select top 1 a_prev.*
      from a a_prev
      where a_prev = a.PositionDate - 5
     ) a_prev5;

请注意,5天的平均差异是最近的值减去6天前的值除以5.

答案 1 :(得分:0)

当我在2个日期之间调整Delta时,我已经有了这种公式。 就像这样:

Select todaypositiondate,
          'D_RealizedSEK'   =       round(sum(realizedccy*spotsek) -  
                                        (SELECT sum(realizedccy*spotsek) 
                                        FROM T1
                                        WHERE todaypositiondate = a.todaypositiondate - 1
                                        GROUP BY todaypositiondate),0)
FROM T1 AS a
    group by todaypositiondate

Ĵ

而不是添加5个公式,只是用-2,-3替换-1 ...我想找到从前5天中选择所有realicedccy的平均总和,最后将它们加在一起并除以5 。