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

postgresql – 如何使用SQLAlchemy执行SELECT DISTINCT ON查询,第1张

概述我要求显示过去30天的支出估算. SpendEstimation每天计算多次.这可以使用简单的SQL查询来实现: SELECT DISTINCT ON (date) date(time) AS date, resource_id , timeFROM spend_estimationWHERE resource_id = '<id>' and time > now() - interv 我要求显示过去30天的支出估算. SpendEstimation每天计算多次.这可以使用简单的SQL查询来实现:
SELECT disTINCT ON (date) date(time) AS date,resource_ID,timeFROM spend_estimationWHERE  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 spendORDER 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 differenceFROM spendORDER 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查询全部内容,希望文章能够帮你解决postgresql – 如何使用SQLAlchemy执行SELECT DISTINCT ON查询所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/1165872.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-01
下一篇 2022-06-01

发表评论

登录后才能评论

评论列表(0条)

保存