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
廣告
© . All rights reserved.