如何计算MySQL中的天数?
让我们首先创建一个表,其中一列作为日期时间,另一列存储日期:
mysql> create table DemoTable ( ShippingDate datetime, CountOfDate int );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable values('2018-01-31',6); mysql> insert into DemoTable values('2016-12-01',15); mysql> insert into DemoTable values('2016-12-01',10); mysql> insert into DemoTable values('2016-12-01',5); mysql> insert into DemoTable values('2019-04-09',3); mysql> insert into DemoTable values('2018-01-31',4); mysql> insert into DemoTable values('2019-04-09',4);
以下是使用select命令显示表中记录的查询:
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)