MySQL按组移动12个月

时间:2014-06-02 01:17:39

标签: mysql group-by sum moving-average

我希望获得过去12个月的总和值,类似于:

Trailing Sum Query

主要区别在于我想要追踪12个月的总和,其中每个组都是独立计算的。这里是样本数据,其中四分之一始终是连续的。

create table keywordsum (date1 datetime, val int, group1 int);
insert keywordsum values
('2011-03-31',10,1),
('2011-06-30',20,1),
('2011-09-30',30,1),
('2011-12-31',40,1),
('2012-03-31',50,1),
('2012-06-30',60,1),
('2010-12-31',1,2),
('2011-03-31',2,2),
('2011-06-30',3,2),
('2011-09-30',4,2),
('2011-12-31',5,2),
('2012-03-31',6,2);

这是所需的输出:

date1,moving_sum,group1
('2011-03-31',NULL,1),
('2011-06-30',NULL,1),
('2011-09-30',NULL,1),
('2011-12-31',100,1),
('2012-03-31',140,1),
('2012-06-30',180,1),
('2010-12-31',NULL,2),
('2011-03-31',NULL,2),
('2011-06-30',NULL,2),
('2011-09-30',10,2),
('2011-12-31',14,2),
('2012-03-31',18,2);

例如,第6行的trailing_sum或group = 1和2012-06-30是第3-6行的总和,或2011-09-30,2011-12-31,2012的group = 1值-03-31和2012-06-30 = 30 + 40 + 50 + 60 = 180。第3行或组= 1和2011-09-30的尾随总和为NULL,因为2011-09-30之前没有四个值。类似地,第2行到最后一行,group = 2和2011-12-31的尾随总和是group = 2值的总和2011-03-31到2011-12-31 = 2 + 3 + 4 + 5 = 14. trailing_sum对于第8行,group = 2和2011-03-31为NULL,因为在group = 2的2010-06-30至2011-03-31之间没有四个值。

当我尝试GROUP BY时,我总是为每个组最后一行。如何获得所需的输出?感谢。

1 个答案:

答案 0 :(得分:0)

我想我明白了。

以下获取移动总和,但前三个值不是NULL

select date1,
       (select sum(val)
        from keywordsum kws2
        where kws2.date1 between kws.date - interval 365+15 day and kws.date and
              kws2.group1 = kws.group1
       ) as moving_sum,
       group1
from keywordsum kws;

为此,请使用case声明:

select date1,
       (select (case when count(*) = 4 then sum(val) end)
        from keywordsum kws2
        where kws2.date1 between kws.date - interval 365+15 day and kws.date and
              kws2.group1 = kws.group1
       ) as moving_sum,
       group1
from keywordsum kws;