Ho un obbligo di visualizzare la stima della spesa per gli ultimi 30 giorni. SpendEstimation viene calcolato più volte al giorno. Ciò può essere ottenuto utilizzando semplici query SQL:Come eseguire SELECT DISTINCT ON query utilizzando SQLAlchemy
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;
Purtroppo non riesco a essere in grado di fare lo stesso utilizzando SQLAlchemy. Crea sempre select distinct su tutte le colonne. La query generata non contiene 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
Manca ON (date)
bit. Se utente query.group_by
- SQLAlchemy aggiunge distinct on
. Anche se non riesco a pensare a una soluzione per un dato problema usando group by.
Provato a utilizzare la funzione in una parte distinta e ordinare per parte pure.
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
)
che ha portato in questo SQL:
SELECT DISTINCT
date(time) AS date,
resource_id,
time,
date(time) AS date # only difference
FROM spend
ORDER BY date, time
che ancora manca DISTINCT ON
.
che dbms stai usando? AFAIK SQLAlchemy supporta DISTINCT ON solo su dialetti specifici – architectonic
Re: @architectonic - http://stackoverflow.com/questions/17223174/returning-distinct-rows-in-sqlalchemy-with-sqlite - vedere la prima risposta – Monkpit
Re @architectonic questo è molto buona domanda - sto usando il database postgresql. – aisbaa