排除ID相同但辅助列值不同的行

时间:2019-05-08 19:29:42

标签: sql oracle filter

如果ID (PK)相同但辅助列值不同,我试图排除记录。

因此在下面的示例中,对于单个E03_Port,我有两个不同的代码E12_PortfNotDefID,因此,基本上,我想排除E12_PortfNotDef记录,如果{ {1}}至E01..码被触发。

E04..

实际结果:

SELECT *
FROM (
  SELECT ID, Code,
    MAX(CASE WHEN Code = 'E01_Matured' THEN 1 Else NULL END) AS Matured,
    MAX(CASE WHEN Code = 'E02_Terminated' THEN 2 Else NULL END) AS Terminated,
    MAX(CASE WHEN Code = 'E03_Port' THEN '3' Else NULL END) AS Port,
    MAX(CASE WHEN Code = 'E04_Swap' THEN 4 Else NULL END) AS Swap,
    MAX(CASE WHEN Code = 'E12_PortfNotDef' THEN '12' Else NULL END) AS Port_Not_Def
  FROM EXCLUDED
  GROUP BY ID, Code
)
WHERE COALESCE(Matured, Terminated, Port, Swap Port_Not_Def) IS NOT NULL
AND ID = '120320AC'
ORDER BY ID;

预期结果:

    ID              Code            Matured     Terminated   Port Swap  Port_Not_Def
    120320AC      E03_Port             3            
    120320AC      E12_PortfNotDef                                             12

2 个答案:

答案 0 :(得分:0)

可以使用row_number()窗口分析函数来应用一个简单的方法:

SELECT *
 FROM (
       SELECT ID, Code,    
              MAX(CASE WHEN Code = 'E01_Matured' THEN 1 Else NULL END) AS Matured,
              MAX(CASE WHEN Code = 'E02_Terminated' THEN 2 Else NULL END) AS Terminated,
              MAX(CASE WHEN Code = 'E03_Port' THEN '3' Else NULL END) AS Port,
              MAX(CASE WHEN Code = 'E04_Swap' THEN 4 Else NULL END) AS Swap,
              MAX(CASE WHEN Code = 'E12_PortfNotDef' THEN '12' Else NULL END) AS Port_Not_Def,
              ROW_NUMBER() OVER (PARTITION BY Code ORDER BY ID, Code) AS RN     
         FROM EXCLUDED
        GROUP BY ID, Code)    
 WHERE COALESCE(Matured, Terminated, Port, Swap Port_Not_Def) IS NOT NULL
   AND ID = '120320AC'
   AND RN = 1
 ORDER BY ID

答案 1 :(得分:0)

我最终限制FROM子句中的ID,以不显示代码为E01-E04的那些ID。