处理 Oracle 中的重复记录 SQL

Handle Duplicate Record in Oracle SQL

我有一个 table 记录如下

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

也就是说,我想 select 基于 STATUS 的数据。

  1. 条件——如果对于相同参数的两种情况,STATUS 都是 ACTIVE - select 首先是 ACTIVE

  2. 条件——如果对于相同参数的两种情况,STATUS 均为 INACTIVE - select 首先出现 INACTIVE

  3. 条件 -- 如果同一参数的状态为活动和非活动 - select 活动

现在我使用下面的查询来像上面那样填充结果,而不使用主键列 (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; 

它显​​示了很好的数据。但是当我像下面这样使用 PRIMARY KEY Column (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; 

使用解析函数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>