การนับ การรวม และการจัดกลุ่มข้อมูล

Python เบื้องต้นสำหรับฐานข้อมูล

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

ฟังก์ชัน SQL

  • เช่น COUNT, SUM
  • from sqlalchemy import func
  • มีประสิทธิภาพมากกว่าการประมวลผลใน Python
  • รวบรวมข้อมูลแบบ Aggregate
Python เบื้องต้นสำหรับฐานข้อมูล

ตัวอย่างการใช้ Sum

from sqlalchemy import func

stmt = select([func.sum(census.columns.pop2008)])
results = connection.execute(stmt).scalar()
print(results)
302876613
Python เบื้องต้นสำหรับฐานข้อมูล

Group by

  • ใช้จัดกลุ่มแถวตามค่าที่เหมือนกัน
Python เบื้องต้นสำหรับฐานข้อมูล

Group by

stmt = select([census.columns.sex, 
  func.sum(census.columns.pop2008)])

stmt = stmt.group_by(census.columns.sex)
results = connection.execute(stmt).fetchall()
print(results)
[('F', 153959198), ('M', 148917415)]
Python เบื้องต้นสำหรับฐานข้อมูล

Group by

  • รองรับการจัดกลุ่มหลายคอลัมน์ในรูปแบบเดียวกับ order_by()
  • คอลัมน์ที่เลือกทั้งหมดต้องถูกจัดกลุ่มหรือ Aggregate ด้วยฟังก์ชัน
Python เบื้องต้นสำหรับฐานข้อมูล

Group by หลายคอลัมน์

stmt = select([census.columns.sex,
        census.columns.age,
        func.sum(census.columns.pop2008)
    ])

stmt = stmt.group_by(census.columns.sex, census.columns.age)
results = connection.execute(stmt).fetchall() print(results)
[('F', 0, 2105442), ('F', 1, 2087705), ('F', 2, 2037280),
('F', 3, 2012742), ('F', 4, 2014825), ('F', 5, 1991082),
('F', 6, 1977923), ('F', 7, 2005470), ('F', 8, 1925725), ...
Python เบื้องต้นสำหรับฐานข้อมูล

การจัดการ ResultSet จากฟังก์ชัน

  • SQLAlchemy สร้าง "ชื่อคอลัมน์" ให้ฟังก์ชันใน ResultSet โดยอัตโนมัติ
  • ชื่อคอลัมน์มักเป็น func_# เช่น count_1
  • ใช้เมธอด label() เพื่อตั้งชื่อแทน
Python เบื้องต้นสำหรับฐานข้อมูล

การใช้ label()

print(results[0].keys())
['sex', u'sum_1']
stmt = select([census.columns.sex,
        func.sum(census.columns.pop2008).label('pop2008_sum')
    ])

stmt = stmt.group_by(census.columns.sex)
results = connection.execute(stmt).fetchall() print(results[0].keys())
['sex', 'pop2008_sum']
Python เบื้องต้นสำหรับฐานข้อมูล

มาฝึกกันเถอะ!

Python เบื้องต้นสำหรับฐานข้อมูล

Preparing Video For Download...