Oracle 重复数据去重筛选,group by 进阶

1. Oracle去重,group by 筛选

1. 先group by找到每个人最新的数据插入时间(insert_time)
SELECT
    T.u_name,
    MAX( T.insert_time ) AS t_inserttime 
FROM
    user_test T 
GROUP BY
    T.u_name

2. 通过insert_time作为条件表关联的条件筛选出每个人最新的数据
SELECT
    T1.id,
    T1.u_name,
    T1.u_sex,
    T1.u_phone,
    T1.insert_time,
    T1.update_by 
FROM
    `user_test` T1,
    ( SELECT T2.u_name, MAX( T2.insert_time ) AS t_inserttime FROM user_test T2 GROUP BY T2.u_name ) T3 
WHERE
    T1.u_name = T3.u_name 
    AND T1.insert_time = T3.t_inserttime

解法2:通过row_number()over()函数解决 (适用于Oracle)
row_number() over()函数的主要功能是分组排序,实现类似group by + order by的效果

SELECT
    FI.* 
FROM
    ( SELECT T.*, ROW_NUMBER ( ) OVER ( PARTITION BY T.u_name ORDER BY T.insert_time DESC ) RW FROM user_test T ) FI 
WHERE
    FI.RW =1

这里partition by实现了根据用户名进行分组,order by对结果集根据插入时间进行排序,row_number()函数将每一组的行数单独标注了出来。最后我们取rw=1的数据,也就取到了每个重复用户数据的最新一条数据

2更灵活,适合处理复杂筛选

    原文作者:我笔记
    原文地址: https://blog.csdn.net/y1535623813/article/details/121472363
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞