废话不多说,直接干货。
一、oracle去重
1、创建测试数据
create table test_duplicate_removal(
c001 number,
c002 varchar2(100)
);
insert into test_duplicate_removal values(101, 'aa');
insert into test_duplicate_removal values(102, 'aa');
insert into test_duplicate_removal values(103, 'aa');
insert into test_duplicate_removal values(104, 'bb');
insert into test_duplicate_removal values(105, 'bb');
insert into test_duplicate_removal values(106, 'cc');
insert into test_duplicate_removal values(107, 'cc');
insert into test_duplicate_removal values(108, 'dd');
2、使用row_number() over()函数根据c002列去重
创建一个rn列,根据c002进行分组,每个小组内再根据c001的值进行排序。
select c001,c002, row_number() over(partition by c002 order by c001 desc) rn from test_duplicate_removal
通过rn筛选值为1的行,同时也就对c002进行了去重
select * from (select c001,c002, row_number() over(partition by c002 order by c001 desc) rn from test_duplicate_removal) t where t.rn=1
二、python的pandas模块去重方法
1、将数据库数据导出保存为csv
2、pandas实现sql里排序函数row_number() over()功能
import pandas as pd
# 读取csv数据
df = pd.read_csv('test_duplicate_removal.csv')
print('打印原始数据:')
print(df)
# 此处等价于sql里的排序函数row_number() over()功能
df['rn'] = df['c001'].groupby(df['c002']).rank()
print()
print('根据c002分组,根据c001组内排序:')
print(df)
# 去重
print()
print('去重,筛选rn=1的行:')
print(df[df['rn'] == 1])
运行结果