SEQ |
LIMIT | ORDER | VAL |
ID001 | N | 1 | 1 |
ID001 | Y | 3 | 2 |
ID001 | N | 4 | 3 |
ID001 | Y | 3 | 4 |
ID001 | N | 1 | 5 |
ID002 | N | 4 | 1 |
ID002 | Y | 2 | 2 |
ID002 | Y | 2 | 3 |
ID002 | N | 1 | 4 |
ID002 | N | 4 | 5 |
ID001, ID002 별로 그룹바이하여 LIMIT값이 Y인 값의 ORDER값보다 작은것들 중에서 VAL값이 최소값인것을 찾아야 하는데 잘안되네요.. ㅜ
설명드리자면 ID001을 기준으로 LIMIT가 'Y'인 놈을 찾으면 일단 두ROW가 나오게되고
ID001 Y 3 2 / ID001 Y 3 4 해당ROW의 ORDER값 3 보다 작은놈을 찾습니다.
LIMIT='Y' 인 ROW의 ORDER값은 항상 동일합니다.
그럼 ID001 N 1 1 / ID001 N 1 5 ROW가 나오게되고 이중에서 VAL값이 작은 ID001 N 1 1의 값이 최종 선택됩니다.
[결과]
ID001 | N | 1 | 1 |
ID002 | N | 1 | 4 |
두ROW중 VAL값이 작은 ROW.. <--- 이조건은 삭제합니다.
ID001 | N | 1 | 1 |
WITH t AS ( SELECT 'ID001' seq, 'N' lmt, 1 ord, 1 val FROM dual UNION ALL SELECT 'ID001', 'Y', 3, 2 FROM dual UNION ALL SELECT 'ID001', 'N', 4, 3 FROM dual UNION ALL SELECT 'ID001', 'Y', 3, 4 FROM dual UNION ALL SELECT 'ID001', 'N', 1, 5 FROM dual UNION ALL SELECT 'ID002', 'N', 4, 1 FROM dual UNION ALL SELECT 'ID002', 'Y', 2, 2 FROM dual UNION ALL SELECT 'ID002', 'Y', 2, 3 FROM dual UNION ALL SELECT 'ID002', 'N', 1, 4 FROM dual UNION ALL SELECT 'ID002', 'N', 4, 5 FROM dual ) SELECT seq, lmt, ord, val FROM (SELECT seq, lmt, ord, val , RANK() OVER(PARTITION BY seq ORDER BY val) rk FROM (SELECT seq, lmt, ord, val , MIN(DECODE(lmt, 'Y', ord)) OVER(PARTITION BY seq) ord_min_y FROM t ) WHERE ord < ord_min_y ) WHERE rk = 1 ;
WITH TT(SEQ, LIMIT, "ORDER", VAL) AS ( SELECT 'ID001', 'N', 1, 1 FROM DUAL UNION ALL SELECT 'ID001', 'Y', 3, 2 FROM DUAL UNION ALL SELECT 'ID001', 'N', 4, 3 FROM DUAL UNION ALL SELECT 'ID001', 'Y', 3, 4 FROM DUAL UNION ALL SELECT 'ID001', 'N', 1, 5 FROM DUAL UNION ALL SELECT 'ID002', 'N', 4, 1 FROM DUAL UNION ALL SELECT 'ID002', 'Y', 2, 2 FROM DUAL UNION ALL SELECT 'ID002', 'Y', 2, 3 FROM DUAL UNION ALL SELECT 'ID002', 'N', 1, 4 FROM DUAL UNION ALL SELECT 'ID002', 'N', 4, 5 FROM DUAL ) SELECT SEQ, LIMIT, "ORDER", VAL FROM ( SELECT AA.SEQ, AA.LIMIT, AA."ORDER", AA.VAL , ROW_NUMBER () OVER (PARTITION BY AA.SEQ ORDER BY AA.VAL) RN FROM TT AA , (SELECT DISTINCT SEQ, "ORDER" FROM TT WHERE LIMIT = 'Y') BB WHERE AA.SEQ = BB.SEQ AND AA."ORDER" < BB."ORDER" ) WHERE RN = 1 ;