postgresql - 如何使用 SQLAlchemy 执行 SELECT DISTINCT ON 查询

标签 postgresql flask sqlalchemy

我需要显示过去 30 天的支出估算。 SpendEstimation 每天计算多次。这可以使用简单的 SQL 查询来实现:

SELECT DISTINCT ON (date) date(time) AS date, resource_id , time
FROM spend_estimation
WHERE
  resource_id = '<id>'
  and time > now() - interval '30 days'
ORDER BY date DESC, time DESC;

不幸的是,我似乎无法使用 SQLAlchemy 做同样的事情。它总是在所有列上创建 select distinct。生成的查询不包含 distinct on

query = session.query(
    func.date(SpendEstimation.time).label('date'),
    SpendEstimation.resource_id,
    SpendEstimation.time
).distinct(
    'date'
).order_by(
    'date',
    SpendEstimation.time
)
SELECT DISTINCT
    date(time) AS date,
    resource_id,
    time 
FROM spend
ORDER BY date, time

它缺少 ON(日期) 位。如果我使用 query.group_by - 然后 SQLAlchemy 添加 distinct on。虽然我想不出使用 group by 解决给定问题的解决方案。


尝试在不同的部分使用函数并按部分排序。

query = session.query(
    func.date(SpendEstimation.time).label('date'),
    SpendEstimation.resource_id,
    SpendEstimation.time
).distinct(
    func.date(SpendEstimation.time).label('date')
).order_by(
    func.date(SpendEstimation.time).label('date'),
    SpendEstimation.time
)

这导致了这个 SQL:

SELECT DISTINCT
       date(time) AS date,
       resource_id,
       time,
       date(time) AS date # only difference
FROM spend
ORDER BY date, time

仍然缺少 DISTINCT ON

最佳答案

您的 SqlAlchemy 版本可能是罪魁祸首。

Sqlalchemy with postgres. Try to get 'DISTINCT ON' instead of 'DISTINCT'

此错误报告的链接: https://bitbucket.org/zzzeek/sqlalchemy/issues/2142

没有向后移植到 0.6 的修复,看起来它已在 0.7 中修复。

关于postgresql - 如何使用 SQLAlchemy 执行 SELECT DISTINCT ON 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32964938/

相关文章:

python - 在 Windows 7 中安装 py-bcrypt 时出现编译器错误

python - Flask WTForm 验证 SelectField 失败...为什么?

python - 如何从时钟进程 Heroku Flask 访问我的 PostgreSQL 数据库?

python - 将 SqlSoup 与数据库 View 一起使用时出错

python - pandas 在 csv 上提高 OutOfBoundsDatetime 但不在 sql 上提高 OutOfBoundsDatetime

macos - 正在使用的 Postgres 应用程序错误数据目录

postgresql - SQLAlchemy 核心 CREATE TEMPORARY TABLE AS

perl - 如何在 shell 脚本中从 postgresql 中提取 pg_backend_pid 并将其传递给另一个进程?

mysql - SQLAlchemy 更新时间在 Alembic 修订版中不起作用

python - 使用 python 将压缩的 SQL 转储导入 Postgresql