从数据库创建序列Sum

时间:2017-10-09 08:49:32

标签: mysql function stored-procedures

Hello all Well我正在尝试进行序列输出,我需要每月添加一个值,这将从我的数据库中获取,所以我想要的是从所有输入数据中添加的值在同一个月,然后将其添加到值(a),然后下个月(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';

所以我想计算工作序列evey月 让我们说效率表中的数据看起来像:

    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 

我希望看起来如此:

  

A = sum jan,b =和feb,c = b sum可以======&gt; A = 2.42,b = 3.9,c = 4.76

1 个答案:

答案 0 :(得分: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:=@rt + 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:=@rt + 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