Oracle/SQL2012. 4. 10. 11:40

연속 상승 구간을 조회해보자.


예제를 위해 아래와 같이 테이블을 생성하자.

-- 1
DROP TABLE t1 PURGE;
CREATE TABLE t1 (cd VARCHAR2(1), dt DATE, vl NUMBER);

INSERT INTO t1 VALUES ('A', DATE '2050-01-01', 100);
INSERT INTO t1 VALUES ('A', DATE '2050-01-02', 200);
INSERT INTO t1 VALUES ('A', DATE '2050-01-03', 300);
INSERT INTO t1 VALUES ('A', DATE '2050-01-04', 400);
INSERT INTO t1 VALUES ('A', DATE '2050-01-05', 500);
INSERT INTO t1 VALUES ('A', DATE '2050-01-06', 400);
INSERT INTO t1 VALUES ('A', DATE '2050-01-07', 500);
INSERT INTO t1 VALUES ('A', DATE '2050-01-08', 600);
INSERT INTO t1 VALUES ('A', DATE '2050-01-09', 700);
INSERT INTO t1 VALUES ('A', DATE '2050-01-10', 500);
COMMIT;


아래와 같이 LAG 함수를 사용하여 전일대비 값인 df를 생성하고, 전체 순번과 df 별 순번의 차를 기준으로 cn을 계산하면 연속 상승 구간을 조회할 수 있다.

-- 2
WITH w1 AS (
SELECT a.*
     , NVL (SIGN (vl - LAG (vl) OVER (PARTITION BY cd ORDER BY dt)), 0) AS df
  FROM t1 a)
SELECT *
  FROM (SELECT a.*
             , COUNT (*) OVER (PARTITION BY cd, rn) AS cn
          FROM (SELECT a.*
                     , ROW_NUMBER () OVER (PARTITION BY cd ORDER BY dt)
                     - ROW_NUMBER () OVER (PARTITION BY cd, df ORDER BY dt) AS rn
                  FROM w1 a) a
         WHERE df = 1)
 WHERE cn >= 3;

CD DT          VL DF RN CN
-- ---------- --- -- -- --
A  2050-01-02 200  1  1  4
A  2050-01-03 300  1  1  4
A  2050-01-04 400  1  1  4
A  2050-01-05 500  1  1  4
A  2050-01-07 500  1  2  3
A  2050-01-08 600  1  2  3
A  2050-01-09 700  1  2  3

7 행이 선택되었습니다.


Posted by 정희락_