当前位置:网站首页>实战演练 | 在 MySQL 中计算每日平均日期或时间间隔
实战演练 | 在 MySQL 中计算每日平均日期或时间间隔
2022-07-30 09:06:00 【Navicat中国】
在先前的文章先前的文章中,我们使用 Navicat for SQL Server 将 SQL Server 中给定列的平均每日计数制成表格。在今天的后续文章中,我们将通过计算基于开始日期和结束日期列的每日平均日期或时间间隔来稍微提高难度系数。出于演示目的,我将使用 Navicat Premium 和 MySQL。
计算以日为单位的电影租借时间
在 Sakila 示例数据库的 rental 表中,有两个日期字段代表一个时间间隔:它们是租借日期和归还日期。无疑,这两个字段存储租借电影的日期时间以及归还电影的日期时间。

考虑到这一点,假设我们需要编写一个查询来显示每日电影租借的平均长度。第一步将是计算所有电影租借的时长。以下是在 Navicat 中查询的样子:

若要将 rental_date 从日期时间转换为纯日期,我们可以使用 DATE() 函数。它接受任何有效的日期或日期时间表达式。
日数可以使用 MySQL DATEDIFF() 函数计算。它返回两个日期或日期时间之间的日数。Navicat 提供的自动完成代码功能可以帮助我们使用 DATEDIFF() 函数。当你开始键入单词时,会出现一个弹出列表,其中包含有关模式、表或视图、列以及存储过程和函数的建议。以下是建议列表中的 DATEDIFF() 函数:

选择一个函数后,它会以可通过 TAB 键聚焦、颜色编码、输入参数的格式插入到代码中的光标位置,以便快速输入:

关于时间
对于较短的时间范围,可以使用 TIMEDIFF() 代替 DATEDIFF()。它返回以秒为单位的时差。对于更长的时间间隔,你可以将返回值除以 60 转换成分钟,再将返回值除以 60 转换成小时。
按日分组结果
下一步是按日分组结果。这可以通过 GROUP BY 子句完成。它使我们可以将诸如 COUNT() 和 AVG() 之类的聚合函数应用于每个 rental_date 的租用日数。以下是加入了 GROUP BY 子句的查询:

你会注意到,我将 avg_days_rented 舍入到小数点后一位。否则,我们将获得 4 个精度点,这对于我们的目的而言可能有点多!
总结
幸亏 MySQL 有许多日期或时间函数,基于开始和结束日期列来计算每日平均日期或时间间隔比以前容易得多。此外,Navicat 功能丰富的 SQL 编辑器为几乎所有数据库实体(包括模式、表、列以及函数和存储过程)提供自动完成代码功能,这能进一步简化查询编写。如果你对 Navicat Premium 感兴趣,可以免费试用 14 天!
往期回顾
边栏推荐
- MySQL中使用IN 不会走索引分析以及解决办法
- sort函数使用cmp出错Line 22: Char 38: error: reference to non-static member function must be called
- 涛思 TDengine 2.6+优化参数
- 20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission
- The FPGA based protocol 2: the I2C read and write E squared PROM
- STM8L_库函数-模板搭建
- 【云原生】Kubernetes入门详细讲解
- leetcode 剑指 Offer 10- I. 斐波那契数列
- An article to understand service governance in distributed development
- 编程界的“躲猫猫”比赛 | 每日趣闻
猜你喜欢
随机推荐
国外资源加速下载器,代码全部开源
2022杭电多校第一场
使用 Neuron 接入 Modbus TCP 及 Modbus RTU 协议设备
无法定位程序输入点ucrtbase.abort于动态链接库api-ms-win-crt-runtime-|1-1-0.dll上
信号完整性测试
Use the R language to read the csv file into a data frame, and then view the properties of each column.
The sword refers to offer 48: the longest non-repeating substring
echart图表清空上一次数据
How to run dist file on local computer
Concise Notes on Integrals - Types of Curve Integrals of the First Kind
水电表预付费系统
积分专题笔记-积分的定义
leetcode 剑指 Offer 15. 二进制中1的个数
Circuit analysis: constant current source circuit composed of op amp and triode
知识图谱之Cypher语言的使用
leetcode 剑指 Offer 58 - I. 翻转单词顺序
20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission
Unreal Engine Graphic Notes: could not be compiled. Try rebuilding from source manually. Problem solving
BaseQuickAdapter方法getBindingAdapterPosition
MySQL【运算符】









