postgresql – 如何使用SQLAlchemy执行SELECT DISTINCT ON查询
发布时间:2020-12-13 16:17:10 所属栏目:百科 来源:网络整理
导读:我要求显示过去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 B
我要求显示过去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’ 此错误报告的链接: 一个修复程序没有向后移植到0.6,看起来像是固定在0.7. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |