求sql 语句 - rolling 3 month average

elkxie 2014-08-08 09:29:15
数据结构如下,很简单: 月份和销售额

YYMM QTY
201301 100
201302 300
........
201401 200
------
201405 400
201406 300
201407 800

希望的结果是从201401开始,每个月显示的从这个开始的三个月的均值
YYMM AVG_QTY
201401 AVG QTY of (201401,201312,201311)
201402 AVG QTY of (201402,2014101,201312)

比如 201407 的值应该是 (400+300+800)/3 = 500

...全文
214 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
elkxie 2014-08-08
  • 打赏
  • 举报
回复
谢谢子查询的方法,引申一下,如果还有个ID 字段在外面, 结构 如 ID, YYMM, sales, 子查询的连接如何调整?谢谢
引用 2 楼 chenglongwei 的回复:
也可以通过子查询来解决!感谢楼上的测试环境语句
create table test (YYMM varchar(10),QTY int)
insert test 
select '201310',100 union all
select '201311',300 union all
select '201312',220 union all
select '201401',100 union all
select '201402',500 union all
select '201403',700 union all
select '201404',800 union all
select '201405',100 union all
select '201406',500 union all
select '201407',200


--子查询做运算
SELECT yymm,
qty=(SELECT SUM(a.qty)/3 FROM test a WHERE a.yymm<=test.yymm AND a.yymm>=left(CONVERT(varchar(100),dateadd(MM,-2,CONVERT(datetime,test.YYMM+'01')),112),6)) 
FROM dbo.test WHERE yymm>='201401'
chenglongwei 2014-08-08
  • 打赏
  • 举报
回复
也可以通过子查询来解决!感谢楼上的测试环境语句
create table test (YYMM varchar(10),QTY int)
insert test 
select '201310',100 union all
select '201311',300 union all
select '201312',220 union all
select '201401',100 union all
select '201402',500 union all
select '201403',700 union all
select '201404',800 union all
select '201405',100 union all
select '201406',500 union all
select '201407',200


--子查询做运算
SELECT yymm,
qty=(SELECT SUM(a.qty)/3 FROM test a WHERE a.yymm<=test.yymm AND a.yymm>=left(CONVERT(varchar(100),dateadd(MM,-2,CONVERT(datetime,test.YYMM+'01')),112),6)) 
FROM dbo.test WHERE yymm>='201401'
  • 打赏
  • 举报
回复
笨方法


create table test (YYMM varchar(10),QTY int)
insert test 
select '201310',100 union all
select '201311',300 union all
select '201312',220 union all
select '201401',100 union all
select '201402',500 union all
select '201403',700 union all
select '201404',800 union all
select '201405',100 union all
select '201406',500 union all
select '201407',200

select a.YYMM,(a.QTY+b.QTY+c.QTY)/3
from test a
	left join test b
	on a.YYMM=left(CONVERT(varchar(100),dateadd(MM,1,CONVERT(datetime,b.YYMM+'01')),112),6)
	left join test c
	on a.YYMM=left(CONVERT(varchar(100),dateadd(MM,2,CONVERT(datetime,c.YYMM+'01')),112),6)
where a.YYMM>left(CONVERT(varchar(100),'2014-01-01',112),6)
/*
201401	206
201402	273
201403	433
201404	666
201405	533
201406	466
201407	266
*/

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧