我希望返回列中最常出现的事件。我知道如何在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"}
答案 0 :(得分:1)
假设您正在分组的列被称为"类别":
from sqlalchemy import func, desc
session.query(
func.count(tablename.id).label('qty')
).group_by(tablename.category
).order_by(desc('qty'))
答案 1 :(得分:0)
@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'))