我目前有一个类似于以下内容的mysql表:
+---------------------+------+-------+-------+-------+
| datetime | name | flag1 | flag2 | flag3 |
+---------------------+------+-------+-------+-------+
| 2018-05-06 00:00:05 | john | 0 | 2 | 1 |
| 2018-05-06 00:00:10 | john | 1 | 0 | 1 |
| 2018-05-06 00:00:15 | john | 1 | 1 | 1 |
| 2018-05-06 00:00:05 | troy | 1 | 1 | 1 |
| 2018-05-06 00:00:10 | troy | 1 | 1 | 1 |
| 2018-05-06 00:00:15 | troy | 1 | 0 | 1 |
| 2018-05-05 00:00:05 | john | 1 | 0 | 0 |
| 2018-05-05 00:00:10 | john | 1 | 1 | 0 |
| 2018-05-05 00:00:15 | john | 0 | 1 | 0 |
| 2018-05-05 00:00:05 | troy | 2 | 1 | 1 |
| 2018-05-05 00:00:10 | troy | 3 | 1 | 0 |
| 2018-05-05 00:00:15 | troy | 3 | 1 | 3 |
| 2018-05-04 00:00:05 | john | 1 | 1 | 1 |
| 2018-05-04 00:00:10 | john | 1 | 1 | 1 |
| 2018-05-04 00:00:15 | john | 0 | 0 | 2 |
| 2018-05-04 00:00:05 | troy | 3 | 1 | 0 |
| 2018-05-04 00:00:10 | troy | 1 | 1 | 1 |
| 2018-05-04 00:00:15 | troy | 1 | 1 | 1 |
+---------------------+------+-------+-------+-------+
我希望在每个独特的日子将其合并为每个名称的每个标志值的累计值。
我正在努力将其合并到这个:
+------------+------+-------------+-------------+-------------+
| date | name | total_flag1 | total_flag2 | total_flag3 |
+------------+------+-------------+-------------+-------------+
| 2018-05-06 | john | 2 | 3 | 3 |
| 2018-05-06 | troy | 3 | 2 | 3 |
| 2018-05-05 | john | 2 | 2 | 0 |
| 2018-05-05 | troy | 8 | 3 | 4 |
| 2018-05-04 | john | 2 | 2 | 4 |
| 2018-05-04 | troy | 5 | 3 | 2 |
+------------+------+-------------+-------------+-------------+
我正在处理的实际表包含300多个唯一名称,每行包含288个(每天5分钟间隔)行,每行包含一个标记值。
我知道我可以通过执行以下操作来为每个日期/名称执行此操作:
@flag1Cuml := 0;
@flag2Cuml := 0;
@flag2Cuml := 0;
SELECT
DATE(datetime) as date,
name,
(@flag1Cuml := @flag1Cuml + flag1) as total_flag1,
(@flag2Cuml := @flag2Cuml + flag2) as total_flag2,
(@flag2Cuml := @flag2Cuml + flag3) as total_flag3
WHERE
name = 'John'
AND DATE(datetime) = '2018-05-06'
显然,由于我的桌子很大,所以这丝毫不是最佳的。我确信可以在一个嵌套查询中执行此操作,但我是mysql的新手,并且不确定如何获得我需要的内容。
理想情况下,我希望在可能的情况下使用此查询生成新视图。
答案 0 :(得分:1)
我没有看到有关这些数字的累积信息。我看到一个简单的group by
:
select date(datetime) as date, name, sum(flag1) as flag1,
sum(flag2) as flag2, sum(flag3) as flag3
from t
group by date(datetime), name;