微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/postgresql/192077.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐