sql—mysql中按日期和用户列进行的累计和分组

jei2mxaa  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(532)

我当前有一个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'

很明显,这一点都不理想,因为我的table太大了。我确信可以在一个嵌套查询中完成这一切,但我对mysql还很陌生,不确定如何获得我需要的东西。
理想情况下,如果可能的话,我想使用这个查询来生成一个新视图。

qij5mzcb

qij5mzcb1#

我看不出这些数字有什么累加。我看到一个简单的 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;

相关问题