如何删除oracle查询中的重复记录

时间:2016-03-30 13:55:52

标签: mysql oracle oracle11g

表1:

ID  CODE_ID
123  1010
234  1415

表2:

ID STATE CODE_ID
123  9   1010
123  13  1010
234  20  1415
234  30  1410

我的查询:

select a.ID, b.STATE, b.CODE_ID
from Table1 a, Table2 b
where a.ID = b.ID 
and a.CODE_ID = b.CODE_ID

当前查询结果:

ID STATE CODE_ID
123  9   1010
123  13  1010
234  20  1415    --------record dont want to see in result.

我的预期结果

ID STATE CODE_ID
123  9   1010
123  13  1010

你能看看我该怎样做才能从我的查询中删除那条记录

3 个答案:

答案 0 :(得分:1)

这是使用分析函数的替代方法,假设您在t2中的行之后每个id和code_id有超过1行:

select id,
       state,
       code_id
from   (select t2.id,
               t2.state,
               t2.code_id,
               count(*) over (partition by t2.id, t2.code_id) cnt
        from   table1 t1
               inner join table2 t2 on (t1.id = t2.id
                                        and t1.code_id = t2.code_id))
where  cnt > 1;

如果您在每个ID和code_id只有两行的行之后,请改用where cnt = 2

如果您使用不同的状态处理多行,则将count(*)替换为count(distinct t2.state)(例如,如果id和code_id有两行,但两者都有相同的州,你想排除那种情况。)

答案 1 :(得分:1)

这是使用分析的另一种方式...

  with Table1 as (
           select 123 id, 1010 code_id from dual union all
           select 234 id, 1415 code_id from dual 
           ),
        Table2 as (
           select 123 id, 9  state, 1010 code_id from dual union all
           select 123 id, 13 state, 1010 code_id from dual union all
           select 234 id, 20 state, 1415 code_id from dual union all
           select 234 id, 20 state, 1415 code_id from dual union all
           select 234 id, 20 state, 1410 code_id from dual union all
           select 234 id, 30 state, 1410 code_id from dual 
           ),
     w_sub as (
        select a.id aid, b.ID  bid, b.STATE, b.CODE_ID,
              count(a.id) over (partition by b.id) chk,
              count(*) over (partition by b.id) chkt
        from Table2 b
           left outer join
              Table1 a
              on a.ID = b.ID 
              and a.CODE_ID = b.CODE_ID
        )
  select bid  id, state, code_id
    from w_sub
   where chk = chkt
  /

          ID      STATE    CODE_ID
  ---------- ---------- ----------
         123         13       1010
         123          9       1010

答案 2 :(得分:0)

试试这个:

SELECT a.ID, b.STATE, b.CODE_ID
FROM Table1 a, Table2 b
WHERE 
    a.ID = b.ID 
    AND a.CODE_ID = b.CODE_ID
    AND a.CODE_ID IN
(
    SELECT CODE_ID FROM Table2 
    GROUP BY CODE_ID HAVING COUNT(*) > 1
)