2015-10-06 14 views
6

私は過去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 

+0

どのdbmsを使用していますか? AFAIK SQLAlchemyは特定の方言に対してのみDISTINCT ONをサポートします – architectonic

+0

Re:@architectonic - http://stackoverflow.com/questions/17223174/returning-distinct-rows-in-sqlalchemy-with-sqlite-最初の回答を参照 – Monkpit

+0

Re @architectonic thats very良い質問 - 私はpostgresqlデータベースを使用しています。 – aisbaa

答えて

0

愚かな質問:'date'の代わりにSpendEstimation.dateを区別しようとしましたか?

EDIT:SELECTの名前付き列を使用しようとしています。 SQLAlchemyはそれほどスマートではありません。 funcの式をdistinct()呼び出しに渡してみてください。

+0

こんにちは、ありがとう、SpendEstimation.date列は存在しません、それはspend_timeから計算されます。モデルに「virtual_column」を追加することは可能かもしれませんが、確かではありません。 私は 'func'をdistinctに渡そうとしましたが、予想通りにクエリを変更しませんでした。 – aisbaa

+0

OK。別の愚かな質問:どのバージョンのSQLAlchemyを使用していますか? – alyssackwan

+0

また、 'func'アプローチを使って更新されたPythonコードは何ですか? 'text()'の '' date''をラップしようとしましたか? – alyssackwan

関連する問題