-----------------------------------------------------------------------------模拟数据---------------------------------------------------------------------------
--创建测试数据及表结构
create table tablename(N1 varchar2(10), N2 varchar2(10), N3 varchar2(10));
insert into tablename 1, 2, 3 from dual union allselect 1, 2, 3 from dual union allselect 5, 2, 3 from dual union allselect 10, 20, 30 from dual ;commit;select*from tablename;
--数据集(针对指定列,查出去重后的结果集)
--N1 N2 N3
--1 2 3
--1 2 3
--5 2 3
--10 20 30
-----------------------------------------------------------------------------distinct-----------------------------------------------------------------------------
select distinct t1.* from tablename t1;
N1 N2 N3
10 20 30
1 2 3
5 2 3
--方法局限性很大,因为它只能对全部查询的列做去重。如果我想对N2,N3去重,那我的结果集中就只能有N2,N3列,而不能有N1列。
select distinct t1.N2, N3 from tablename t1
N2 N3
2 3
20 30
--不过它也是最简单易懂的写法。
-----------------------------------------------------------------------------row_number-----------------------------------------------------------------------------
select * from (select t1.*,
row_number() over(partition by t1.N2, t1.N3 order by 1) rn
from tablename t1) t1 where t1.rn = 1;
N1 N2 N3 RN
1 2 3 1
10 20 30 1
--写法上要麻烦不少,但是有更大的灵活性。
--针对指定列,查出所有重复的行
-----------------------------------------------------------------------------count having-----------------------------------------------------------------------------
select * from tablename t
where (t.N2, t.N3) in (select t1.N2, t1.N3
from tablename t1
group by t1.N2, t1.N3
having count(1) > 1)
N1 N2 N3
1 2 3
1 2 3
5 2 3
--要查两次表,效率会比较低。不推荐。
------------------------------------------------------------------------------count over----------------------------------------------------------------------------
select * from (select t1.*,
count(1) over(partition by t1.N2, t1.N3) rn
from tablename t1) t1 where t1.rn > 1;
N1 N2 N3 RN
1 2 3 3
1 2 3 3
5 2 3 3
--只需要查一次表,推荐。
本文来自博客园,作者:旧路人,转载请注明原文链接:https://www.cnblogs.com/snrj/p/17045797.html