欢迎访问宙启技术站
智能推送

使用SQLAlchemy.sql.func对数据进行分类统计

发布时间:2023-12-19 01:57:45

SQLAlchemy.sql.func是SQLAlchemy库中的一个模块,用于执行数据库查询中的SQL聚合函数。SQLAlchemy是一个Python的ORM(对象关系映射)工具,可以方便地操作关系型数据库。

使用SQLAlchemy.sql.func可以对数据进行分类统计,例如计算平均值、求和、计数等操作。下面是SQLAlchemy.sql.func的几个常用函数及其用法的示例。

1. count()

count()函数用于计算特定字段的非空记录数。例如,假设我们有一个名为Students的数据表,其中包含学生的ID、姓名和年龄。我们想要统计学生的人数。

from sqlalchemy import create_engine
from sqlalchemy import select
from sqlalchemy import func

# 创建数据库引擎
engine = create_engine('mysql+pymysql://username:password@host:port/db_name')

# 连接数据库
with engine.connect() as conn:
    # 查询学生人数
    stmt = select([func.count()]).select_from(Students)
    result = conn.execute(stmt).scalar()

print(f"学生人数为:{result}")

2. sum()

sum()函数用于计算特定字段的总和。例如,我们想要计算一份销售报表中的销售总额。

from sqlalchemy import create_engine
from sqlalchemy import select
from sqlalchemy import func

# 创建数据库引擎
engine = create_engine('mysql+pymysql://username:password@host:port/db_name')

# 连接数据库
with engine.connect() as conn:
    # 查询销售总额
    stmt = select([func.sum(Sales.amount)]).select_from(Sales)
    result = conn.execute(stmt).scalar()

print(f"销售总额为:{result}")

3. avg()

avg()函数用于计算特定字段的平均值。例如,我们想要计算一组学生成绩的平均分。

from sqlalchemy import create_engine
from sqlalchemy import select
from sqlalchemy import func

# 创建数据库引擎
engine = create_engine('mysql+pymysql://username:password@host:port/db_name')

# 连接数据库
with engine.connect() as conn:
    # 查询平均分
    stmt = select([func.avg(Students.score)]).select_from(Students)
    result = conn.execute(stmt).scalar()

print(f"平均分为:{result}")

4. min()和max()

min()函数用于计算特定字段的最小值,max()函数用于计算特定字段的最大值。例如,我们想要计算一组商品价格的最低价和最高价。

from sqlalchemy import create_engine
from sqlalchemy import select
from sqlalchemy import func

# 创建数据库引擎
engine = create_engine('mysql+pymysql://username:password@host:port/db_name')

# 连接数据库
with engine.connect() as conn:
    # 查询最低价和最高价
    stmt = select([func.min(Products.price), func.max(Products.price)]).select_from(Products)
    result = conn.execute(stmt).fetchone()

min_price, max_price = result
print(f"最低价为:{min_price}")
print(f"最高价为:{max_price}")

5. group_by()

group_by()函数用于按照特定字段对数据进行分组。例如,我们想要统计每个学生的科目数量。

from sqlalchemy import create_engine
from sqlalchemy import select
from sqlalchemy import func

# 创建数据库引擎
engine = create_engine('mysql+pymysql://username:password@host:port/db_name')

# 连接数据库
with engine.connect() as conn:
    # 统计每个学生的科目数量
    stmt = select([Students.name, func.count(Subjects.id)]).select_from(Students).join(Subjects)
    stmt = stmt.group_by(Students.name)
    results = conn.execute(stmt).fetchall()

for name, count in results:
    print(f"{name}: {count}")

上述是SQLAlchemy.sql.func的一些常用函数及其用法的示例。通过使用这些函数,可以方便地对数据进行分类统计,进行更复杂的数据库查询和分析操作。