![](/img/trans.png)
[英]Rolling 12 months SUM from latest available data with varchar YearMonth
[英]SQL Rolling 3 months total with 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只是一个整数,没有编码为日期。 任何帮助表示赞赏
如果您没有月份缺少数据(如示例数据),则可以执行以下操作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.