ITeye博客

ORACLE 分析函数实例[处理冗余数据]

MoocherMan · 2012-11-14 15:56 · 数据库--ORACLE及综合 · 数据库 · Markdown

一.创建数据库表结构


create table test1(
   id number primary key,
   code1 VARCHAR2(20) not null,
   code2 varchar2(20) not null,
   code3 number
) 

二.创建测试数据

    id      code1    code2   code3

======================================= 1 1 1 a 30 2 2 1 b 40 3 3 1 c 50 4 4 2 a 26 5 5 2 e 11 6 6 2 f 33 7 7 3 g 25 8 8 3 t 25 9 9 1 a 21

三.业务描述

1.查询code1,code2 两个字段全部出现重复的记录信息


select t.* from (
       select id,code1,code2,code3,count(*) over (partition by code1,code2) as 重复次数 from test1
) t where t.重复次数 > 1 

运行结果:


        id      code1    code2   code3    重复次数 
==================================================
1	1	1	a	30	2
2	9	1	a	21	2

2.业务追加:在以上基础上追加条件,只显示code3值最小的记录


select t.* from (
       select id,code1,code2,code3,count(*) over (partition by code1,code2) as 重复次数,min(code3) over(partition by code1,code2) as c3 from test1
) t where t.重复次数 > 1 and t.code3 = t.c3

执行结果:


        id      code1    code2   code3    重复次数 
==================================================
1	9	1	a	21	2

3.追加业务:在以上基础上继续追加条件,如果code3值最小的记录有多条,那么只显示其中rowid最小的那条记录 为了体现这个业务 特在库表中加入一条数据

    id        code1 code2     code3

===================================================== 10 1 a 21


select * from (
select t.*,min(rowid) over(partition by code1,code2,code3) as m_rwid from (
       select id,code1,code2,code3,count(*) over (partition by code1,code2) as 重复次数,min(code3) over(partition by code1,code2) as c3,
        rowid from test1
) t where t.重复次数 > 1 and t.code3 = t.c3
) where m_rwid = rowid
--三层的select 这sql写的比冗余数据都冗余 有好想法的请留言 - -

执行结果:


==================================================================================
1	9	1	a	21	3	21	AAARbLAABAAAV9RAAI	AAARbLAABAAAV9RAAI

关于over函数,可以点击 http://www.iteye.com/topic/575434

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。