在 MySQL 中获取两个给定日期之间的记录总和
mysqlmysqli database
为此,请使用 BETWEEN 关键字。让我们首先创建一个 −
mysql> create table DemoTable1444 -> ( -> Value int, -> PurchaseDate datetime -> ); Query OK, 0 rows affected (0.45 sec)
使用 insert 在表中插入一些记录 −
mysql> insert into DemoTable1444 values(40,'2019-01-10'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable1444 values(100,'2019-10-03'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1444 values(170,'2019-11-21'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1444 values(70,'2018-12-05'); Query OK, 1 row affected (0.11 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1444;
这将产生以下输出 −
+-------+---------------------+ | Value | PurchaseDate | +-------+---------------------+ | 40 | 2019-01-10 00:00:00 | | 100 | 2019-10-03 00:00:00 | | 170 | 2019-11-21 00:00:00 | | 70 | 2018-12-05 00:00:00 | +-------+---------------------+ 4 rows in set (0.00 sec)
以下查询用于获取两个给定日期之间的总和 −
mysql> select sum(Value) from DemoTable1444 where PurchaseDate between '2019-10-02' and '2019-12-31';
这将产生以下输出 −
+------------+ | sum(Value) | +------------+ | 270 | +------------+ 1 row in set (0.02 sec)