2010-06-18 57 views
1

選擇行我有一個表像這樣Oracle查詢與唯一代碼

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

我只想選擇,其代碼只出現在一行的記錄。即在這種情況下,行代碼爲33和34 ..因爲它們在此表中只出現一次。

我如何編寫一個查詢爲

回答

2
SELECT C1, C2, C3, Code FROM tablename 
WHERE Code IN 
(
    SELECT Code FROM tablename 
    GROUP BY Code 
    HAVING count(Code) = 1 
) 
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。當心在代碼列

3

NULL值如果你只想要一個傳過你的數據,那麼你可以使用此查詢:

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' 

問候, 羅布。