Oracle查询以选择具有唯一代码的行

时间:2010-06-18 08:18:21

标签: sql oracle

我有一张这样的表

C1 C2 C3 Code
1   2  3   33
1   2  3   34
2   4  1   14
1   2  3   14

我想只选择那些代码只出现在单行中的记录。即,在这种情况下,行代码为33和34 ..因为它们在此表中只出现一次。

如何为该

编写查询

3 个答案:

答案 0 :(得分:3)

如果您只希望对数据进行一次传递,则可以使用此查询:

SQL> create table mytable (c1,c2,c3,code)
  2  as
  3  select 1, 2, 3, 33 from dual union all
  4  select 1, 2, 3, 34 from dual union all
  5  select 2, 4, 1, 14 from dual union all
  6  select 1, 2, 3, 14 from dual
  7  /

Table created.

SQL> set autotrace on
SQL> select max(c1) c1
  2       , max(c2) c2
  3       , max(c3) c3
  4       , code
  5    from mytable
  6   group by code
  7  having count(*) = 1
  8  /

        C1         C2         C3       CODE
---------- ---------- ---------- ----------
         1          2          3         33
         1          2          3         34

2 rows selected.


Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE
   1    0   FILTER
   2    1     SORT (GROUP BY)
   3    2       TABLE ACCESS (FULL) OF 'MYTABLE'

此致 罗布。

答案 1 :(得分:2)

SELECT C1, C2, C3, Code FROM tablename
WHERE Code IN
(
   SELECT Code FROM tablename
   GROUP BY Code 
   HAVING count(Code) = 1
)

答案 2 :(得分:0)

select C1, C2, C3, Code 
from tablename T1
where not exists ( select T2.exclude
                     from tablename T2
                    where T2.Code = T1.Code
                      and T2.rowid <> T1.rowid
                 )

PS。注意代码列中的NULL值