python - 在 SQLAlchemy 的数组列中查找最频繁的值

标签 python database flask sqlalchemy flask-sqlalchemy

我希望返回列中出现频率最高的值。我知道如何在 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'))

关于python - 在 SQLAlchemy 的数组列中查找最频繁的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28033656/

相关文章:

database - Docker Swarm 如何处理数据库(PostgreSQL)复制?

c# - 如何使用单个连接执行两个 command.ExecuteNonQuery() 方法?

postgresql - 如何使用 Flask 模型在 postgres 中存储图像

python - Python 中的前瞻算法

python - SqlAlchemy 中单独的 REST 请求的单独 session 对象?

python - 匹配 Python 中的特定字符串,除非缺少给定模式

python - SQLAlchemy 使用过滤器映射表列

python - 如何从 eclipse 执行 Robot 测试用例,它将命令行列表参数作为输入?

database - VBA Excel 语法错误查询表达式插入语句中缺少运算符

python - 当我运行程序时 flask 错误