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

前端 未结 10 1807
深忆病人
深忆病人 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:39

    Please try this,

    SELECT 
    c.Id,
    c.name,
    (SELECT pi.price FROM purchase pi WHERE pi.Id = MAX(p.Id)) AS [LastPurchasePrice]
    FROM customer c INNER JOIN purchase p 
    ON c.Id = p.customerId 
    GROUP BY c.Id,c.name;
    

提交回复
热议问题