根据 MySQL 中相似的日期汇总各列的对应值?
为此,请使用聚集函数 SUM() 和 GROUP BY。我们首先创建一个表 -
mysql> create table DemoTable1522 -> ( -> ProductPurchaseDate date, -> NumberOfProduct int -> ); Query OK, 0 rows affected (1.51 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1522 values('2019-01-21',45); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1522 values('2018-12-31',78); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1522 values('2019-01-21',67); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1522 values('2019-03-01',56); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1522 values('2018-01-21',97); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1522 values('2019-01-21',47); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable1522;
这将产生以下输出 -
+---------------------+-----------------+ | ProductPurchaseDate | NumberOfProduct | +---------------------+-----------------+ | 2019-01-21 | 45 | | 2018-12-31 | 78 | | 2019-01-21 | 67 | | 2019-03-01 | 56 | | 2018-01-21 | 97 | | 2019-01-21 | 47 | +---------------------+-----------------+ 6 rows in set (0.00 sec)
以下是根据 MySQL 中的日期统计列的查询 -
mysql> select ProductPurchaseDate,sum(NumberOfProduct) from DemoTable1522 -> group by ProductPurchaseDate;
这将产生以下输出 -
+---------------------+----------------------+ | ProductPurchaseDate | sum(NumberOfProduct) | +---------------------+----------------------+ | 2019-01-21 | 159 | | 2018-12-31 | 78 | | 2019-03-01 | 56 | | 2018-01-21 | 97 | +---------------------+----------------------+ 4 rows in set (0.00 sec)
广告