documentazione dice:
DISTINCT ON (expression [, ...]) keeps only the first row of each set of rows where the given expressions evaluate to equal. [...] Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. [...] The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s).
Official documentation
quindi dovrete aggiungere il address_id
all'ordine da.
In alternativa, se si sta cercando la riga completa contenente il prodotto acquistato più recente per ogni address_id
e il risultato ordinato per purchased_at
, si sta tentando di risolvere un problema N maggiore per gruppo che può essere risolto dal seguenti approcci:
La soluzione generale che dovrebbe funzionare nella maggior parte dei DBMS:
SELECT t1.* FROM purchases t1
JOIN (
SELECT address_id, max(purchased_at) max_purchased_at
FROM purchases
WHERE product_id = 1
GROUP BY address_id
) t2
ON t1.address_id = t2.address_id AND t1.purchased_at = t2.max_purchased_at
ORDER BY t1.purchased_at DESC
Una soluzione più PostgreSQL orientata in base alla risposta di @ HKF:
SELECT * FROM (
SELECT DISTINCT ON (address_id) *
FROM purchases
WHERE product_id = 1
ORDER BY address_id, purchased_at DESC
) t
ORDER BY purchased_at DESC
problema chiarito, esteso e risolto qui: Selecting rows ordered by some column and distinct on another
fonte
2012-03-20 22:08:32
tuo clausola ordine è purchased_at non address_id.Can fate la vostra domanda chiara. – Teja
il mio ordine ha acquistato perché lo voglio, ma Postgres richiede anche l'indirizzo (vedi messaggio di errore). –
Completamente risposto qui - http://stackoverflow.com/questions/9796078/selecting-rows-ordered-by-some-column-and-disctinct-on-another grazie a http://stackoverflow.com/users/ 268273/mosty-mostacho –