2017-10-09 81 views
0

你好所有那么我想做一个序列输出,我需要一个值将被添加每个月将从我的数据库中采取,所以我想要的价值是(b)+这个值(a)告诉上个月,我知道它听起来令人困惑,但我会尝试回答任何问题解释得我希望我能得到帮助... 我会写什么,我想在存储过程中进行:从数据库中创建一个序列总和

SELECT * FROM mysqldatabase.usecases 
A = Sum Work Where SingOffDate <='2017-01-30' and SingOffDate >= '2017-01-01' , B = Sum Work sum A Where SingOffDate <='2017-02-30' and SingOffDate >= '2017-02-01', 
C = Sum Work sum B Where SingOffDate <='2017-03-30' and SingOffDate >= '2017-03-01', D = Sum Work sum C Where SingOffDate <='2017-04-30' and SingOffDate >= '2017-04-01'; 

所以我想计算工作顺序埃维月 比方说数据来自效率表的外观像:

Work | SingOffDate 
    2 | 11/01/2017 
    0.12 | 12/01/2017 
    0.3 | 5/01/2017 
    0.48 | 11/02/2017 
    1 | 15/02/2017 
    0.86 | 09/03/207 

,我想像的reselt:

A =总和一月,B = A总和二月,C = B总和可以======> A = 2.42 ,b = 3.9,C = 4.76

+0

这看起来像一组简单的总和同比和月。这将有助于澄清您是否可以将样本数据和预期结果添加到您的问题中 - 以文本或sqlfiddle的形式。 –

+0

@P.Salmon我会添加样本的数据和结果 –

回答

0

我还没有在你预期的结果清楚,但可能做

drop table if exists t; 
create table t(Work decimal(10,2) ,SingOffDate date); 
insert into t values 
( 2 , str_to_date('11/01/2017','%d/%m/%Y')), 
( 0.12 , str_to_date('12/01/2017','%d/%m/%Y')), 
( 0.3 , str_to_date('5/01/2017','%d/%m/%Y')), 
( 0.48 , str_to_date('11/02/2017','%d/%m/%Y')), 
( 1 , str_to_date('15/02/2017','%d/%m/%Y')), 
( 0.86 , str_to_date('09/03/2017','%d/%m/%Y')); 

select max(case when yyyymm = '2017/1' then RunningTotal else 0 end) as a, 
     max(case when yyyymm = '2017/2' then RunningTotal else 0 end) as b, 
     max(case when yyyymm = '2017/3' then RunningTotal else 0 end) as c 
from 
(
select yyyymm,work,@rt:[email protected] + work as RunningTotal 
from 
(
select concat(year(singoffdate),'/',month(singoffdate)) yyyymm, 
      sum(work) as work 
from t 
group by concat(year(singoffdate),'/',month(singoffdate)) 
) t, (select @rt:=0) r 
) u 
; 

凡在最里面的阙我正在按月份和年份总结这项工作,除此之外,我计算了一个总计,最后我使用条件聚合来调整看起来像这样的结果。

+------+------+------+ 
| a | b | c | 
+------+------+------+ 
| 2.42 | 3.9 | 4.76 | 
+------+------+------+ 
1 row in set (0.00 sec) 

或者,也许你只是想运行总以这种形式

+--------+------+--------------+ 
| yyyymm | work | RunningTotal | 
+--------+------+--------------+ 
| 2017/1 | 2.42 |   2.42 | 
| 2017/2 | 1.48 |   3.9 | 
| 2017/3 | 0.86 |   4.76 | 
+--------+------+--------------+ 
3 rows in set (0.00 sec) 

在这种情况下,使用此查询

select yyyymm,work,@rt:[email protected] + work as RunningTotal 
from 
(
select concat(year(singoffdate),'/',month(singoffdate)) yyyymm, 
      sum(work) as work 
from t 
group by concat(year(singoffdate),'/',month(singoffdate)) 
) t, (select @rt:=0) r 
+0

thxxx,我想要什么 –

相关问题