我需要显示过去 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/