如何在 MySQL 中计算天数?
首先,我们创建一个表,其中一列为日期时间,另一列存储天数
mysql> create table DemoTable ( ShippingDate datetime, CountOfDate int ); Query OK, 0 rows affected (0.52 sec)
以下是使用插入命令在表中插入某些记录的查询
mysql> insert into DemoTable values('2018-01-31',6); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('2016-12-01',15); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable values('2016-12-01',10); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('2016-12-01',5); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('2019-04-09',3); Query OK, 1 row affected (1.05 sec) mysql> insert into DemoTable values('2018-01-31',4); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('2019-04-09',4); Query OK, 1 row affected (0.14 sec)
以下是使用选择命令从表中显示记录的查询
mysql> select *from DemoTable;
这将产生以下带日期和数量的输出
+---------------------+-------------+ | ShippingDate | CountOfDate | +---------------------+-------------+ | 2018-01-31 00:00:00 | 6 | | 2016-12-01 00:00:00 | 15 | | 2016-12-01 00:00:00 | 10 | | 2016-12-01 00:00:00 | 5 | | 2019-04-09 00:00:00 | 3 | | 2018-01-31 00:00:00 | 4 | | 2019-04-09 00:00:00 | 4 | +---------------------+-------------+ 7 rows in set (0.00 sec)
以下是获取天数之和的查询
mysql> select date(ShippingDate),sum(CountOfDate) from DemoTable group by date(ShippingDate);
这将产生以下输出
+--------------------+------------------+ | date(ShippingDate) | sum(CountOfDate) | +--------------------+------------------+ | 2018-01-31 | 10 | | 2016-12-01 | 30 | | 2019-04-09 | 7 | +--------------------+------------------+ 3 rows in set (0.00 sec)
广告