sql去除重复数据语句(sql中三种去重的方式)

废话不多说,直接干货。

一、oracle去重

1、创建测试数据

ORACLE去重,python的pandas模块实现相同去重功能ORACLE去重,python的pandas模块实现相同去重功能
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');
ORACLE去重,python的pandas模块实现相同去重功能ORACLE去重,python的pandas模块实现相同去重功能

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
ORACLE去重,python的pandas模块实现相同去重功能ORACLE去重,python的pandas模块实现相同去重功能

通过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
ORACLE去重,python的pandas模块实现相同去重功能ORACLE去重,python的pandas模块实现相同去重功能

二、python的pandas模块去重方法

1、将数据库数据导出保存为CSV

ORACLE去重,python的pandas模块实现相同去重功能ORACLE去重,python的pandas模块实现相同去重功能

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])

运行结果

ORACLE去重,python的pandas模块实现相同去重功能ORACLE去重,python的pandas模块实现相同去重功能
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至624739273@qq.com举报,一经查实,本站将立刻删除。
Like (0)
柳的头像

相关推荐

发表回复

Please Login to Comment
微信
微信
SHARE
TOP
要想花得少,就用购宝。话费电费9折起,官方公众号:购宝