SELECT x.user_name, x.activity, x.start_date, x.end_dateFROM(select a.*, b.activity_cou,row_number()over(partitionby a.user_name order by a.datediff DESC ) as rnfrom (select*, datediff(end_date,start_date) as datediff from leetcode.ex_1369_user_activity) a left join (select user_name,count(activity) as activity_cou -- 只有1個活動的用戶不參與題目要求的判斷from leetcode.ex_1369_user_activitygroup by user_name) b ON a.user_name=b.user_name) xWHERE x.activity_cou =1or (x.activity_cou>1and x.rn=2);