私は過去30日間の費用見積もりを表示する必要があります。 SpendEstimationは1日に複数回計算されます。これは、単純なSQLクエリを使用して達成することができます:SQLAlchemyを使用してSELECT DISTINCT ONクエリを実行する
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 (date)
ビットが欠落しています。私のユーザがquery.group_by
の場合、SQLAlchemyはdistinct on
を追加します。グループを使って与えられた問題の解を考えることはできませんが。
機能を別の部分でも、部分的にも使用して試しました。このSQLの結果
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
)
:まだDISTINCT ON
が欠落している
SELECT DISTINCT
date(time) AS date,
resource_id,
time,
date(time) AS date # only difference
FROM spend
ORDER BY date, time
。
どのdbmsを使用していますか? AFAIK SQLAlchemyは特定の方言に対してのみDISTINCT ONをサポートします – architectonic
Re:@architectonic - http://stackoverflow.com/questions/17223174/returning-distinct-rows-in-sqlalchemy-with-sqlite-最初の回答を参照 – Monkpit
Re @architectonic thats very良い質問 - 私はpostgresqlデータベースを使用しています。 – aisbaa