2017-04-05 37 views
0

您好我有,如果交易被处理其中有账户,yearmonth和贸易计数SQL滚动3个月总有Yearmonth

account Yearmonth Trade_count 
XXXXX  201701  1 
XXXXX  201701  0 
XXXXX  201702  1 
XXXXX  201703  1 
XXXXX  201704  1 
XXXXX  201704  1 
XXXXX  201705  1 

的trade_count为1的数据集和0,如果没有处理

我想输出这样

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

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

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 

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

+0

哪有失踪几个月? –

+0

您正在使用哪个SQL?现代SQL具有__window函数___,它对滚动总计非常理想。我假设'Yearmonth'是你自己的设备? – Manngo

+0

如果'yearmonth'是一个整数,那么比较是否存在问题,比如'201611 + 3'和'201701'? – Manngo

回答

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