How to select only the latest rows for each user?

前端 未结 2 896
天涯浪人
天涯浪人 2021-01-28 14:23

My table looks like this:

id  | user_id | period_id | completed_on
----------------------------------------
1   | 1       | 1         | 2010-01-01
2   | 2                


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-28 15:01

    Seems like this should work using MAX and a subquery:

    SELECT t.Id, t.User_Id, t.Period_Id, t.Completed_On
    FROM my_table t
       JOIN (SELECT Max(completed_on) Max_Completed_On, t.User_Id
             FROM my_table
             GROUP BY t.User_ID
             ) t2 ON
          t.User_Id = t2.User_Id AND t.Completed_On = t2.Max_Completed_On
    

    However, if you potentially have multiple records where the completed_on date is the same per user, then this could return multiple records. Depending on your needs, potentially adding a MAX(Id) in your subquery and joining on that would work.

提交回复
热议问题