Python中使用sqlalchemy.sql.func进行聚合操作的示例代码
发布时间:2023-12-14 01:05:35
Python中使用sqlalchemy.sql.func进行聚合操作的示例代码如下:
from sqlalchemy import create_engine, Column, Integer, String, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# 创建连接
engine = create_engine('mysql+pymysql://username:password@localhost:3306/database')
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
# 定义模型
class Person(Base):
__tablename__ = 'persons'
id = Column(Integer, primary_key=True)
name = Column(String(50))
age = Column(Integer)
location = Column(String(50))
# 查询年龄的平均值
average_age = session.query(func.avg(Person.age)).scalar()
print("Average Age: ", average_age)
# 查询年龄的最大值和最小值
min_age, max_age = session.query(func.min(Person.age), func.max(Person.age)).one()
print("Min Age: ", min_age)
print("Max Age: ", max_age)
# 查询年龄大于25岁的人数
age_greater_than_25 = session.query(func.count()).filter(Person.age > 25).scalar()
print("People older than 25: ", age_greater_than_25)
# 查询不同地区的人数
people_per_location = session.query(Person.location, func.count()).group_by(Person.location).all()
print("People per Location: ")
for location, count in people_per_location:
print(location, count)
# 关闭连接
session.close()
这里使用了一个名为"persons"的表,包含了id、name、age和location四个字段。
示例代码中展示了几个常见的聚合操作,包括计算年龄的平均值、最大值和最小值,以及查询年龄大于25岁的人数和不同地区的人数。
这里使用了sqlalchemy的函数avg、min、max和count进行聚合计算,并结合filter和group_by进行筛选和分组。最后,通过scalar和all方法获取聚合结果。
需要注意的是,示例代码中的连接字符串需要替换为你自己的数据库连接信息。
