使用MySQL计算累积值

时间:2017-03-30 17:44:01

标签: mysql select

我有这张桌子:

//Use findElements
List<WebElement> elements = driver.findElements(By.xpath("//*[@id='eError']"));
if(elements.size() > 0)
{
    System.out.println(elements.get(0).getText())
}

我需要创建下一个输出表

Month_Year              MV                    MI
----------------------------------------------------------
August 2016              3                    100
October 2016             2                    150
September 2016           1                    100
January 2017             4                    200

在第M个月,对于AMV列,AMV是该月和月M之前所有AV的累计值。例如,AMV在2016年9月的4月份是#4;因为在&#39; 8月16日&#39; 2016年9月&#39; AV为3和1。同样适用于AMI。如何才能做到这一点?。请注意,Month_Year列不一定是有序的。感谢

其他信息 使用DATE_FORMAT(original_Date,&#39;%Y%m&#39;)后,我能够将第一个表格转换为:

Month_Year               MV       AMV          MI     AMI
----------------------------------------------------------
January 2016             0        0            0      0
...
July 2016                0        0            0      0 
August 2016              3        3           100    100
September 2016           1        4           100    200
October 2016             2        6           150    350
November 2016            0        6           0      350
December 2016            0        6           0      350
January 2017             4        10          200    550

这可以简化问题吗?为什么不使用DATE_FORMAT(original_Date,&#39;%m%Y&#39;)?

1 个答案:

答案 0 :(得分:1)

月份格式是一个很大的特征,你必须以某种方式克服它。对于这个例子,我创建了一个MEMORY表months,并且我使用了这个表的几个连接。

create table months (month_year_int int, month_year varchar(30)) engine=memory;
insert months 
select 201601 as month_year_int, 'January 2016' as month_year
      union all select 201602, 'February 2016'
      union all select 201603, 'March 2016'
      union all select 201604, 'April 2016'
      union all select 201605, 'May 2016'
      union all select 201606, 'June 2016'
      union all select 201607, 'July 2016'
      union all select 201608, 'August 2016'
      union all select 201609, 'September 2016'
      union all select 201610, 'October 2016'
      union all select 201611, 'November 2016'
      union all select 201612, 'December 2016'
      union all select 201701, 'January 2017'
;

如果您为数据使用了合适的模型,那么所有这些都可以避免。无论如何,这是一个解决方案,不使用My-Sql专有变量模式(rextester demo here):

select 
    x.month_year, 
    coalesce(t.mv, 0) MV, 
    sum(y.mv) as AMV, 
    coalesce(t.mi, 0) AMV, 
    sum(y.mi) as AMI from 
(
    select 
        m.month_year_int, 
        m.month_year, 
        coalesce(t.mv, 0) as mv, 
        coalesce(t.mi) as mi
    from months m left join test t on m.month_year = t.month_year 
) x 
left join 
(
    select 
        m.month_year_int, 
        m.month_year, 
        coalesce(t.mv, 0) as mv, 
        coalesce(t.mi) as mi
    from months m
        left join test t on m.month_year = t.month_year 
) y on x.month_year_int > y.month_year_int - 1
left join test t on x.month_year = t.month_year
group by x.month_year_int
order by x.month_year_int
;
相关问题