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

前端 未结 10 1810
深忆病人
深忆病人 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
    2020-11-22 09:38

    Try this, It will help.

    I have used this in my project.

    SELECT 
    *
    FROM
    customer c
    OUTER APPLY(SELECT top 1 * FROM purchase pi 
    WHERE pi.customer_id = c.Id order by pi.Id desc) AS [LastPurchasePrice]
    

提交回复
热议问题