Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL滚动3个月总计(含Yearmonth)_Sql - Fatal编程技术网

SQL滚动3个月总计(含Yearmonth)

SQL滚动3个月总计(含Yearmonth),sql,Sql,嗨,我有一个数据集,有账户、年月和交易计数 account Yearmonth Trade_count XXXXX 201701 1 XXXXX 201701 0 XXXXX 201702 1 XXXXX 201703 1 XXXXX 201704 1 XXXXX 201704 1 XXXXX 201705

嗨,我有一个数据集,有账户、年月和交易计数

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
如果交易已处理,则交易单位计数为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

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

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

是否会缺少几个月?您使用的是哪种SQL?现代SQL具有窗口函数,非常适合滚动汇总。我假设
Yearmonth
是您自己的设备?如果
Yearmonth
是一个整数,您在比较
201611+3
201701
时是否有问题?如果一个帐户在一个月内没有进行交易,那么它就丢失了。SQL server 2012 SQL Management studio 2012是否缺少月份?您使用的是哪种SQL?现代SQL具有窗口函数,非常适合滚动汇总。我假设
Yearmonth
是您自己的设备?如果
Yearmonth
是一个整数,您在比较
201611+3
201701
时是否有问题?如果一个帐户在一个月内没有进行交易,那么它就丢失了。SQL server 2012 SQL管理工作室2012