Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การใช้ฟังก์ชัน AVG() ใน MySQL ด้วย Python


ฟังก์ชัน AVG() เป็นหนึ่งในฟังก์ชันทางคณิตศาสตร์ใน MySQL ใช้สำหรับคืนค่าเฉลี่ยของคอลัมน์ตัวเลขในตาราง

ไวยากรณ์

SELECT AVG(column_name) FROM table_name

ขั้นตอนการใช้ AVG() กับตารางใน MySQL ผ่าน Python

  • นำเข้า MySQL Connector

  • สร้างการเชื่อมต่อด้วย connect()

  • สร้างออบเจ็กต์ cursor ด้วย cursor()

  • สร้างคำสั่ง SQL ที่เหมาะสม

  • รันคำสั่งด้วย execute()

  • ปิดการเชื่อมต่อ

สมมติว่ามีตารางชื่อ 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