2015-01-14 81 views
-1

我有一個像下面處理重複記錄在甲骨文SQL

NAME  STATUS   xml_configparamdb_id  xml_configuration_id 
STO   INACTIVE     1      1 
STO   ACTIVE     1      2 
BOS   ACTIVE     1      3 
KYC   INACTIVE     1      4 
KYC   INACTIVE     1      5 
ACC   ACTIVE     1      6 
ACC   ACTIVE     1      7 

現在導致我感興趣的是如下有記錄的表:

NAME  STATUS   xml_configparamdb_id  xml_configuration_id 

STO   ACTIVE     1      2 
BOS   ACTIVE     1      3 
KYC   INACTIVE     1      4 
ACC   ACTIVE     1      6 

也就是說,我想在選擇數據STATUS的基礎。

  1. 條件 - 如果處於Active狀態的相同參數的兩個案例 - 選擇第一次來ACTIVE

  2. 條件 - 如果狀態未激活的相同參數的兩個案例 - 首先選擇未來不活躍

  3. 條件 - 如果處於Active狀態&非活動狀態相同的參數 - 選擇ACTIVE

現在我用下面查詢來填充結果像上面,而無需使用主鍵列(xml_configuration_id)

CURSOR cCnfgTypData IS 
    select distinct name, description, STATUS 
    from stg_xml_cpdb_configuration 
    WHERE process_exec_num = 1 
    AND STATUS = 'ACTIVE' 
    UNION ALL 
    select name, description, STATUS 
    from stg_xml_cpdb_configuration t 
    where process_exec_num = 1 
    and STATUS = 'INACTIVE' 
    and not exists (select * from stg_xml_cpdb_configuration 
    where name = t.name 
    and STATUS = 'ACTIVE') order by name, description; 

它表示細數據。但是,當我執行使用主鍵列(xml_configuration_id)像下面它顯示了所有數據,而不滿足條件

select distinct name, description, STATUS, xml_configparamdb_id, xml_configuration_id 
    from stg_xml_cpdb_configuration 
    WHERE process_exec_num = 1 
    AND STATUS = 'ACTIVE' 
    UNION ALL 
    select name, description, STATUS, xml_configparamdb_id, xml_configuration_id 
    from stg_xml_cpdb_configuration t 
    where process_exec_num = 1 
    and STATUS = 'INACTIVE' 
    and not exists (select * from stg_xml_cpdb_configuration 
    where name = t.name 
    and STATUS = 'ACTIVE') order by name, description; 
+0

作爲參考,http://www.orafaq.com/forum/t/196051/ –

+1

要解釋爲什麼您遇到問題時,不同的關鍵字適用於所有選定列,因爲xml_config_id爲每個行的唯一,不同的將返回每一行 –

回答

0

使用分析功能ROW_NUMBER

SQL> SELECT name, 
    2 status, 
    3 xml_configparamdb_id, 
    4 xml_configuration_id 
    5 FROM 
    6 (SELECT t.*, row_number() over (partition BY name order by status) rn FROM t 
    7 ) 
    8 WHERE rn = 1 
    9 ORDER BY xml_configuration_id 
10/

NAM STATUS XML_CONFIGPARAMDB_ID XML_CONFIGURATION_ID 
--- -------- -------------------- -------------------- 
STO ACTIVE      1     2 
BOS ACTIVE      1     3 
KYC INACTIVE     1     4 
ACC ACTIVE      1     6 

SQL>