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

ais*_*baa 9 postgresql sqlalchemy flask

我要求显示过去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;
Run Code Online (Sandbox Code Playgroud)

不幸的是,我似乎无法使用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
)
Run Code Online (Sandbox Code Playgroud)
SELECT DISTINCT
    date(time) AS date,
    resource_id,
    time 
FROM spend
ORDER BY date, time
Run Code Online (Sandbox Code Playgroud)

它缺少ON (date)一点.如果我用户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
)
Run Code Online (Sandbox Code Playgroud)

这导致了这个SQL:

SELECT DISTINCT
       date(time) AS date,
       resource_id,
       time,
       date(time) AS date # only difference
FROM spend
ORDER BY date, time
Run Code Online (Sandbox Code Playgroud)

哪个仍然缺失DISTINCT ON.

Rob*_*key 1

您的 SqlAlchemy 版本可能是罪魁祸首。

Sqlalchemy 与 postgres。尝试使用“DISTINCT ON”而不是“DISTINCT”

此错误报告的链接: https://bitbucket.org/zzzeek/sqlalchemy/issues/2142

修复程序未向后移植到 0.6,看起来已在 0.7 中修复。