2017-10-09 8 views
0

こんにちはすべて私はシーケンス出力をしようとしています、私はデータベースから取ってくる毎月追加される値が必要です。同じ月のすべての入力データから追加して値(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 

と私は見えるようにしたいreselt:

A =合計1月、B =合計2月、C = Bの合計は======あり> A = 2.42 、B = 3.9、C = 4.76

+0

これは、前年同期比でグループとの単純な合計のように見え、月。サンプル・データと期待される結果をテキストまたはSQLのように質問に追加できるかどうかを明確にするのに役立ちます。 –

+0

@ P.Salmon私はデータとその結果のサンプルを追加します –

答えて

0

私はまだあなたの予想結果に明確ではないですが、これは最も内側QUEで

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 
; 

どこを行うことができますry私は月と年の作業を合計していますが、私は稼動していますが、最終的には条件付き集計を使用して、このような結果をピボットします。

+------+------+------+ 
| 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私が望むもの –

関連する問題