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

我要求显示过去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.

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,time 
FROM spend
ORDER BY date,time

它缺少ON(日期)位.如果我用户query.group_by – 则sqlAlchemy添加了明显的.虽然我想不出解决使用group by的给定问题.

尝试使用不同部分的功能和按部件顺序.

query = session.query(
    func.date(SpendEstimation.time).label('date'),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,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.

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...