mysql 对每个时间戳的所有计数求和

fv2wmkja  于 2022-12-03  发布在  Mysql
关注(0)|答案(2)|浏览(137)

嘿我需要一些SQL查询的帮助我有这个数据

count Timestamp
1     10:05
2     10:06
3     10:07
1     10:08
2     10:09
3     10:10

我想获取每个时间戳到该时刻为止的计数总数

count Timestamp
1     10:05
3     10:06
6     10:07
7     10:08
9     10:09
12    10:10

我尝试了很多事情,最后我遇到的和被它挡住的是:

select sum(count), timestamp 
from table
where timestamp > now() - interval 2 hour
group by date_format(timestamp, '%Y-%m-%d %h:%i')

但这样一来,我就不会每次都得到一个增加的值,我猜这是因为我使用了group by和时间戳
我在考虑添加一个连接,其中我将不使用group by,但如何获得所需时间戳之前的总和?而不是针对所有表

select sum(count)
from table
jq6vz3qz

jq6vz3qz1#

'count'和'timestamp'实际上都用在SQL语言中,并且可能保留用于某些用途-这取决于您的RDBMS;请考虑将它们重命名为更有意义的名称。
试窗合计SUM()OVER:

SELECT
  count
, timestamp 
, sum(count) over (order by timestamp 
                       rows between unbounded preceding and current row) as CumCount
from table
where timestamp > now() - interval 2 hour
6yt4nkrj

6yt4nkrj2#

示例表:

MariaDB [databasename]> create table quux (count integer, timestamp varchar(12));
Query OK, 0 rows affected (0.010 sec)

MariaDB [databasename]> insert into quux values (1,'10:05'),(2,'10:06'),(3,'10:07'),(1,'10:08'),(2,'10:09'),(3,'10:10');
Query OK, 6 rows affected (0.002 sec)
Records: 6  Duplicates: 0  Warnings: 0

查询以取得累计总和:

MariaDB [databasename]> set @cumsum:=0; select (@cumsum := @cumsum + count) as count, timestamp from quux;
Query OK, 0 rows affected (0.000 sec)

+-------+-----------+
| count | timestamp |
+-------+-----------+
|     1 | 10:05     |
|     3 | 10:06     |
|     6 | 10:07     |
|     7 | 10:08     |
|     9 | 10:09     |
|    12 | 10:10     |
+-------+-----------+
6 rows in set (0.000 sec)

对于这个例子,

MariaDB [databasename]> select version();
+---------------------------------------+
| version()                             |
+---------------------------------------+
| 10.9.3-MariaDB-1:10.9.3+maria~ubu2204 |
+---------------------------------------+
1 row in set (0.000 sec)

相关问题