如何在oracle sql中的表或下一个表中选择最小值

时间:2017-08-01 08:41:22

标签: sql oracle

我有一个包含这些列的表L1_CI_PER_ADDRESS

PER_ID,
SEQ_NUM,
ADDRESS_ID,
ADDRESS_TYPE_XFLG,
START_DT,
END_DT,
SEASON_START_MMDD,
SEASON_END_MMDD,
ADDRESS_PRIO_FLG,
DELIVERABLE_FLG,
VERSION,
LOAD_DATE 

我想选择值为ADDRESS_TYPE_XFLG的{​​{1}}(如果存在)或MAIN-AE(如果第一个不存在)。否则,如果MAIN-ENCORRESPOND-AE不存在,我想选择CORRESPOND-AEMAIN-AE

我该怎么做?我是Oracle SQL新手。我想删除当我选择时返回的重复项。

其中一个问题是某些人ID都有四个(MAIN-EN),所以在这种情况下我只想要返回MAIN-AE, MAIN-EN, CORRESPOND-AE, CORRESPOND-EN

我希望我的问题很明确。

enter image description here

1 个答案:

答案 0 :(得分:0)

这是前n个查询。使用row_number()

select * 
  from (
    select PER_ID, address_id, ADDRESS_TYPE_XFLG, 
           row_number() over (partition by per_id 
                                  order by case ADDRESS_TYPE_XFLG 
                                           when 'MAIN-AE'       then 1 
                                           when 'MAIN-EN'       then 2 
                                           when 'CORRESPOND-AE' then 3
                                           when 'CORRESPOND-EN' then 4
                                           end) as rn
      from L1_CI_PER_ADDRESS)
  where rn = 1

如果某个人拥有两个具有相同标记的地址,那么您需要在case when section之后添加正确的顺序,可能类似于, seq_num desc

测试:

with L1_CI_PER_ADDRESS(PER_ID, address_id, ADDRESS_TYPE_XFLG ) as (
    select 1,  1, 'CORRESPOND-AE' from dual union all
    select 1,  2, 'MAIN-AE'       from dual union all
    select 1,  3, 'CORRESPOND-EN' from dual union all
    select 1,  4, 'MAIN-EN'       from dual union all
    select 2,  5, 'CORRESPOND-AE' from dual union all
    select 3,  6, 'MAIN-AE'       from dual union all
    select 4,  7, 'CORRESPOND-EN' from dual union all
    select 4,  8, 'MAIN-AE'       from dual
    )
select PER_ID, address_id 
  from (
    select PER_ID, address_id, ADDRESS_TYPE_XFLG, 
           row_number() over (partition by per_id 
                                  order by case ADDRESS_TYPE_XFLG 
                                           when 'MAIN-AE'       then 1 
                                           when 'MAIN-EN'       then 2 
                                           when 'CORRESPOND-AE' then 3
                                           when 'CORRESPOND-EN' then 4
                                           end) as rn
      from L1_CI_PER_ADDRESS)
  where rn = 1

输出:

      PER_ID ADDRESS_ID ADDRESS_TYPE_XFLG
  ---------- ---------- -----------------
           1          2 MAIN-AE          
           2          5 CORRESPOND-AE    
           3          6 MAIN-AE          
           4          8 MAIN-AE