使用 Python 解释 MySQL 中 AVG() 函数的用法?
pythonserver side programmingprogramming
AVG() 函数是 MySQL 中的算术函数之一。
顾名思义,AVG() 函数用于返回表中数值列的平均值。
语法
SELECT AVG(column_name) FROM table_name
在 Python 中使用 MySQL 对表使用 AVG() 函数需要遵循的步骤
导入 MySQLl 连接器
使用 connect() 与连接器建立连接
使用 cursor() 方法创建游标对象
使用适当的 mysql 语句创建查询
执行使用 execute() 方法执行 SQL 查询
关闭连接
假设我们有以下名为"Students"的表。
Students
+----------+-----------+ | name | marks | +----------+-----------+ | Rohit | 62 | | Rahul | 75 | | Inder | 99 | | Khushi | 49 | | Karan | 92 | +----------+-----------+
我们想要获取学生的平均分数。
示例
import mysql.connector db=mysql.connector.connect(host="your host", user="your username", password="your password",database="database_name") cursor=db.cursor() query1="SELECT AVG(marks) FROM Students" cursor.execute(query1) avg=cursor.fetchall() print(“Average marks :”,avg) db.close()
输出
Average marks : 75.4