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

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

    Without getting into the code first, the logic/algorithm goes below:

    1. Go to the transaction table with multiple records for the same client.

    2. Select records of clientID and the latestDate of client's activity using group by clientID and max(transactionDate)

         select clientID, max(transactionDate) as latestDate 
         from transaction 
         group by clientID
      
    3. inner join the transaction table with the outcome from Step 2, then you will have the full records of the transaction table with only each client's latest record.

         select * from 
         transaction t 
         inner join (
           select clientID, max(transactionDate) as latestDate
           from transaction 
           group by clientID) d 
         on t.clientID = d.clientID and t.transactionDate = d.latestDate) 
      
    4. You can use the result from step 3 to join any table you want to get different results.

提交回复
热议问题