我还没有在你预期的结果清楚,但可能做
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
这看起来像一组简单的总和同比和月。这将有助于澄清您是否可以将样本数据和预期结果添加到您的问题中 - 以文本或sqlfiddle的形式。 –
@P.Salmon我会添加样本的数据和结果 –