- Peewee 教程
- Peewee - 主页
- Peewee - 概览
- Peewee - 数据库类
- Peewee - 模型
- Peewee - 字段类
- Peewee - 插入新记录
- Peewee - 选择记录
- Peewee - 筛选器
- Peewee - 主键和复合主键
- Peewee - 更新现有记录
- Peewee - 删除记录
- Peewee - 创建索引
- Peewee - 约束
- Peewee - 使用 MySQL
- Peewee - 使用 PostgreSQL
- Peewee - 动态定义数据库
- Peewee - 连接管理
- Peewee - 关系和联接
- Peewee - 子查询
- Peewee - 排序
- Peewee - 计数和聚合
- Peewee - SQL 函数
- Peewee - 检索行元组/字典
- Peewee - 用户定义运算符
- Peewee - 原子事务
- Peewee - 数据库错误
- Peewee - 查询生成器
- Peewee - 与 Web 框架的集成
- Peewee - SQLite 扩展
- Peewee - PostgreSQL 和 MySQL 扩展
- Peewee - 使用 CockroachDB
- Peewee 有用资源
- Peewee - 快速指南
- Peewee - 有用资源
- Peewee - 讨论
Peewee - 计数和聚合
我们可以通过附加 count() 方法来查找任何 SELECT 查询中报告的记录数。例如,以下语句返回 Address 表中 City=’Nasik’ 的行数。
qry=Contacts.select().where (Contacts.City=='Nasik').count() print (qry)
示例
SQL 在 SELECT 查询中有 GROUP BY 子句。Peewee 以 group_by() 方法的形式支持它。以下代码返回 Address 表中按城市划分的姓名计数。
from peewee import *
db = SqliteDatabase('mydatabase.db')
class Contacts(BaseModel):
RollNo = IntegerField()
Name = TextField()
City = TextField()
class Meta:
database = db
db.create_tables([Contacts])
qry=Contacts.select(Contacts.City, fn.Count(Contacts.City).alias('count')).group_by(Contacts.City)
print (qry.sql())
for q in qry:
print (q.City, q.count)
Peewee 发出的 SELECT 查询如下所示 −
('SELECT "t1"."City", Count("t1"."City") AS "count" FROM "contacts" AS "t1" GROUP BY "t1"."City"', [])
输出
根据 Address 表中的示例数据,显示以下输出 −
Chennai 1 Delhi 2 Indore 1 Mumbai 1 Nagpur 1 Nasik 3 Pune 1
广告