Selecting rows ordered by some column and distinct on another

前端 未结 3 1067
天命终不由人
天命终不由人 2020-12-01 07:57

Related to - PostgreSQL DISTINCT ON with different ORDER BY

I have table purchases (product_id, purchased_at, address_id)

Sample data:

| id |         


        
3条回答
  •  天命终不由人
    2020-12-01 08:29

    Your ORDER BY is used by DISTINCT ON for picking which row for each distinct address_id to produce. If you then want to order the resulting records, make the DISTINCT ON a subselect and order its results:

    SELECT * FROM
    (
      SELECT DISTINCT ON (address_id) purchases.address_id, purchases.*
      FROM "purchases"
      WHERE "purchases"."product_id" = 2
      ORDER BY purchases.address_id ASC, purchases.purchased_at DESC
    ) distinct_addrs
    order by distinct_addrs.purchased_at DESC
    

提交回复
热议问题