我希望在列中返回最常出现的事件。我知道如何在SQL中执行此操作,但不知道SQL Alchemy。例如,我有这个数据库和帖子。每个帖子都有一个文本字段和一个类别字段。我希望按顺序返回前3个类别,如下所示:
Post 1: "Text", "Food"
Post 2: "Text", "Games"
Post 2: "Text", "Games"
Post 2: "Text", "News"
Post 2: "Text", "News"
Post 2: "Text", "News"
Post 2: "Text", "Other"
Post 2: "Text", "Food"
会回来:
{"News", "Games", "Food"}
假设您要分组的列称为“类别”:
from sqlalchemy import func, desc
session.query(
func.count(tablename.id).label('qty')
).group_by(tablename.category
).order_by(desc('qty'))
为了返回对象和计数器,@ dylrei答案只丢失了一位
from sqlalchemy import func, desc
session.query(tablename.category, <--- You need to add this
func.count(tablename.id).label('qty')
).group_by(tablename.category
).order_by(desc('qty'))