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

前端 未结 10 1670
深忆病人
深忆病人 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条回答
  •  感情败类
    2020-11-22 09:24

    You haven't specified the database. If it is one that allows analytical functions it may be faster to use this approach than the GROUP BY one(definitely faster in Oracle, most likely faster in the late SQL Server editions, don't know about others).

    Syntax in SQL Server would be:

    SELECT c.*, p.*
    FROM customer c INNER JOIN 
         (SELECT RANK() OVER (PARTITION BY customer_id ORDER BY date DESC) r, *
                 FROM purchase) p
    ON (c.id = p.customer_id)
    WHERE p.r = 1
    

提交回复
热议问题