아래와 같이 테이블에 값이 세팅되어 있을때 LIMIT 필드 조건에 따라 ID를 그룹바이하여 최대값 최소값
구하는 쿼리를 깔끔하게 하고 싶은데 잘안되네요;
조건 : 동일 ID그룹에서 LIMIT 값이 'Y' 인값중 최소값을 가져오며, LIMIT 값이 'Y' 인것이 없으면 'N' 값중 최대값을
가져온다.
ID VAL LIMIT
100 01 N
100 03 Y
100 02 Y
200 03 N
200 03 N
200 04 N
300 01 Y
300 01 N
300 01 N
-------------------------------------------------
원하는 결과..
ID VAL LIMIT
100 02 Y
200 04 N
300 01 Y
val필드에 min(), max()를 각각 걸어 그룹바이한 결과를 union해야하나.. 고민중입니다.ㅠ
with t AS (select '100' ID , '01' val , 'N' LIMIT from dual union all select '100' , '03' , 'Y' from dual union all select '100' , '02' , 'Y' from dual union all select '200' , '03' , 'N' from dual union all select '200' , '03' , 'N' from dual union all select '200' , '04' , 'N' from dual union all select '300' , '01' , 'Y' from dual union all select '300' , '01' , 'N' from dual union all select '300' , '01' , 'N' from dual ) select id , limit , decode(limit , 'Y' , minVal , maxVal) val from (select id,limit,min(val) minVal , row_number() over(partition by id order by limit desc) rnk , max(val) maxVal from t group by id,limit) where rnk = 1
with t (id,val,limit) as (
select 100,'01','N' from dual union all
select 100,'03','Y' from dual union all
select 100,'02','Y' from dual union all
select 200,'03','N' from dual union all
select 200,'03','N' from dual union all
select 200,'04','N' from dual union all
select 300,'01','Y' from dual union all
select 300,'01','N' from dual union all
select 300,'01','N' from dual
)
select id,decode(limit,'Y',MN,'N',MX),LIMIT
FROM (
select id,limit,max(val) keep(dense_rank first order by limit desc) mx
,min(val) keep(dense_rank first order by limit desc) mn
,dense_rank() over(partition by id order by limit desc) dr
from t
group by id,limit
)
where dr = 1