有这样的表mytable,包括user_id,my_value,my_date三列。我想获取每个user_id的最近日期max(my_date)对应的user_id,my_value,my_date。用怎样的SQL实现呢?这里假设每个user_id下日期唯一。
本题来源stackoverflow
本题可以有多种方式实现。
1.使用分析函数max,找出每个user_id分组的max(my_date)。
1.使用分析函数max,找出每个user_id分组的max(my_date)。
select user_id, my_value, my_date from ( select user_id, my_value, my_date, max(my_date) over (partition by user_id) max_my_date from mytable ) where my_date = max_my_date
2.使用分析函数row_number,根据user_id分组后按照my_date排序,取每组第一个。
select user_id, my_value, my_date from ( select user_id, my_value, my_date, row_number() over (partition by user_id order by my_date desc) num from mytable ) where num = 1
3.使用group by和子查询
select A.user_id, A.my_value, A.my_date from mytable A, ( select user_id, max(my_date) as max_my_date from mytable group by user_id ) B where A.user_id = B.user_id and A.my_date = B.max_my_date
4.自关联加左关联
SELECT t1.* FROM mytable t1 LEFT OUTER JOIN mytable t2 ON t1.User_Id = t2.User_Id AND t1.my_date < t2.my_date WHERE t2.User_Id IS NULL;
这个方法很别致,深入理解其含义对理解关联操作很有帮助。它的where条件是找出没有满足做关联条件的记录。而左关联的条件是自关联找出自身user_id下日期大于自己的记录。不满足此条件则表明该记录没有日期大于自己的记录,那就是最大日期了。
其实类似的方法还有很多,以上列出具有代表性的方式而已,供学习参考。
The post 如何找到包含某列最大值的那一行? appeared first on SQLParty.