我有这个表:
Month Year MV MI fullDate
-----------------------------------------------------------------
...
5 2015 1 5 2015-05-01
6 2015 1 10 2015-06-01
7 2015 3 10 2015-07-01
8 2015 2 10 2015-08-01
11 2015 1 10 2015-11-01
1 2016 4 10 2016-01-01
6 2016 1 20 2016-06-01
7 2016 null 10 2016-07-01
8 2016 2 5 2016-08-01
...
我需要创建另一个具有累积值的表:
Month Year AMV AMI
-----------------------------------------------------------------
...
7 2015 3 10
8 2015 5 20
11 2015 6 30
1 2016 10 40
6 2016 11 60
7 2016 0 10
8 2016 2 15
...
累积计算必须从 7 月开始,到次年 6 月结束。在此示例中,累积字段从 2015 年 7 月开始"累积",到 2016 年 6 月结束。这些计算于 2016 年 7 月重新开始,为累积值"计算"提供了另一个周期
我之前也问过类似的问题,但我刚刚发现了累积计算的这种"周期性"。还有一件事...第一个表上的某些值可能为 null,需要将其视为 0。
请告诉我如何做到这一点?
我已经修改了@Sebastian的quer。初始化也在查询中。计数器将每年重置,不需要在哪里
SELECT
(@amv:=IF(MONTH(fulldate)=7,MV, IF(ISNULL(MV), 0, @amv+MV))) AS AMV,
(@ami:=IF(MONTH(fulldate)=7,MI, IF(ISNULL(MI), 0, @ami+MI))) AS AMI,
fullDate
FROM
input
CROSS JOIN ( SELECT @amv := 0, @ami := 0) AS init
ORDER BY fullDate ASC;
样本
mysql> select * from input;
+----+------+------+------------+
| id | MV | MI | fullDate |
+----+------+------+------------+
| 1 | 1 | 10 | 2015-08-01 |
| 2 | 2 | 20 | 2015-09-01 |
| 3 | 3 | 30 | 2015-07-01 |
| 4 | 8 | 33 | 2016-07-01 |
| 5 | 2 | 8 | 2016-08-01 |
+----+------+------+------------+
5 rows in set (0,00 sec)
mysql> SELECT
-> (@amv:=IF(MONTH(fulldate)=7,MV, IF(ISNULL(MV), 0, @amv+MV))) AS AMV,
-> (@ami:=IF(MONTH(fulldate)=7,MI, IF(ISNULL(MI), 0, @ami+MI))) AS AMI,
-> fullDate
-> FROM
-> input
-> CROSS JOIN ( SELECT @amv := 0, @ami := 0) AS init
-> ORDER BY fullDate ASC;
+------+------+------------+
| AMV | AMI | fullDate |
+------+------+------------+
| 3 | 30 | 2015-07-01 |
| 4 | 40 | 2015-08-01 |
| 6 | 60 | 2015-09-01 |
| 8 | 33 | 2016-07-01 |
| 10 | 41 | 2016-08-01 |
+------+------+------------+
5 rows in set (0,00 sec)
mysql>
这可以解决问题:
SET @amv := 0, @ami := 0;
SELECT
(@amv:=IF(ISNULL(MV), 0, @amv+MV)) as AMV,
(@ami:=IF(ISNULL(MI), 0, @ami+MI)) as AMI,
fullDate
FROM
input
WHERE
fullDate >= "2015-07-01" AND
fullDate < "2016-07-01"
ORDER BY fullDate ASC;