Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Documentation says:</p> <blockquote> <p>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).</p> </blockquote> <p><a href="http://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-DISTINCT" rel="noreferrer">Official documentation</a></p> <p>So you'll have to add the <code>address_id</code> to the order by.</p> <p>Alternatively, if you're looking for the full row that contains the most recent purchased product for each <code>address_id</code> and that result sorted by <code>purchased_at</code> then you're trying to solve a greatest N per group problem which can be solved by the following approaches:</p> <p>The general solution that should work in most DBMSs:</p> <pre><code>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 </code></pre> <p>A more PostgreSQL-oriented solution based on @hkf's answer:</p> <pre><code>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 </code></pre> <p>Problem clarified, extended and solved here: <a href="https://stackoverflow.com/questions/9796078">Selecting rows ordered by some column and distinct on another</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload