SQL滚动3个月总计与Yearmonth

时间:2017-04-05 02:10:39

标签: sql

您好我有一个有帐户,年月和交易次数的数据集

Account  Yearmonth    Total_Trades_Month     past_3_month trades
XXXXX      201703           1                       3
XXXXX      201704           2                       3
XXXXX      201705           1                       4

如果交易已处理,则trade_count为1,如果未处理,则为0

我想要这样的输出

select yearmonth, (yearmonth - 3) as 'ym',
 SUM(Case when COMMISSION is not null and Commission > 0 then Trade_Count Else 0 END) as 'TotalTrades',
 sum(CASE when yearmonth between (yearmonth - 3) and yearmonth and commission > 0 then Trade_Count else 0 end) as  'rolling'
 sum(Trade_Count)over(partition by yearmonth)
FROM WEALTHDB.DBO.WF_PM_DOR_DB 
group by  yearmonth
order by yearmonth

到目前为止,我已尝试过:

{{1}}

请注意,yearmonth只是一个整数,并没有编号为日期。任何帮助表示赞赏

1 个答案:

答案 0 :(得分:2)

如果没有数据丢失的月份(如示例数据中所示),您可以执行以下操作:

select account, yearmonth, 
       sum(trade_count) as TotalTrades,
       sum(sum(trade_count)) over (partition by account order by yearmonth
                                   rows between 2 preceding and current row
                                  ) as past_3_month_trades
from WEALTHDB.DBO.WF_PM_DOR_DB 
group by account, yearmonth
order by yearmonth