MySQL查询以开始日期和结束日期计算日期范围内的天数
要计算日期范围内的天数,您需要使用来查找日期之间的差额DATEDIFF()
。
让我们首先创建一个表:
mysql> create table DemoTable730 ( StartDate date, EndDate date );
使用insert命令在表中插入一些记录:
mysql> insert into DemoTable730 values('2019-01-21','2019-07-21'); mysql> insert into DemoTable730 values('2018-10-11','2018-12-31'); mysql> insert into DemoTable730 values('2016-01-01','2016-12-31');
使用select语句显示表中的所有记录:
mysql> select *from DemoTable730;
这将产生以下输出-
+------------+------------+ | StartDate | EndDate | +------------+------------+ | 2019-01-21 | 2019-07-21 | | 2018-10-11 | 2018-12-31 | | 2016-01-01 | 2016-12-31 | +------------+------------+ 3 rows in set (0.00 sec)
以下是查询日期范围内的天数的查询:
mysql> select ABS(DATEDIFF(StartDate,EndDate)) AS Days from DemoTable730;
这将产生以下输出-
+------+ | Days | +------+ | 181 | | 81 | | 365 | +------+ 3 rows in set (0.00 sec)