sql - 计算每季度的平均值
问题描述
我有不同年份的数据如下:
yearmonth value1
--------- ------
2016/01 33
2016/02 22
2016/03 22
2016/04 22
2016/05 22
2016/06 25
2016/07 44
2016/08 44
2016/09 44
2016/10 66
2016/11 44
2016/12 34
我想计算value1
每季度的平均值。季度应考虑如下:
Quarter 1 = month 01 till month 03
Quarter 2 = month 01 till month 06
Quarter 3 = month 01 till month 09
Quarter 4 = month 01 till month 12
我尝试使用 over 但它没有获取正确的数据。
解决方案
在 SQL 服务器 2008 中:
我做了 1 个季度,您可以尝试类似的方法:
create table calculation
(
yearmonth varchar(200),
value1 float
);
insert into calculation values('2016/01',33);
insert into calculation values('2016/02',22);
insert into calculation values('2016/03',22);
insert into calculation values('2016/04',22);
insert into calculation values('2016/05',22);
insert into calculation values('2016/06',25);
select
avg(case when yearmonth between '2016/01' and '2016/03' then value1 end) as qtr1
from calculation
注意:以正确的格式存储日期