SQL join: selecting the last records in a one-to-many relationship

前端 未结 10 1802
深忆病人
深忆病人 2020-11-22 08:48

Suppose I have a table of customers and a table of purchases. Each purchase belongs to one customer. I want to get a list of all customers along with their last purchase in

10条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 09:33

    If you're using PostgreSQL you can use DISTINCT ON to find the first row in a group.

    SELECT customer.*, purchase.*
    FROM customer
    JOIN (
       SELECT DISTINCT ON (customer_id) *
       FROM purchase
       ORDER BY customer_id, date DESC
    ) purchase ON purchase.customer_id = customer.id
    

    PostgreSQL Docs - Distinct On

    Note that the DISTINCT ON field(s) -- here customer_id -- must match the left most field(s) in the ORDER BY clause.

    Caveat: This is a nonstandard clause.

提交回复
热议问题