by 궁금한넘 [SQL Query] 이전값 LAG GROUP BY [2021.03.18 19:07:16]
조건에 의해 조회된 값이 다음과 같을때 동일한 과코드라도 이전값이 다르면 1씩 증가하여 나타내고 싶습니다. 쿼리로 가능할런지요? 아니면 어떤식으로 접근해야 할까요?
과코드 | 그룹 |
AAA | 1 |
AAA | 1 |
AAA | 1 |
AAA | 1 |
BBB | 2 |
BBB | 2 |
AAA | 3 |
AAA | 3 |
BBB |
4 |
sum() over로 해봤습니다~
with t as ( select 'AAA' code from dual union all select 'AAA' code from dual union all select 'AAA' code from dual union all select 'AAA' code from dual union all select 'BBB' code from dual union all select 'BBB' code from dual union all select 'AAA' code from dual union all select 'AAA' code from dual union all select 'BBB' code from dual ) select code, sum(flag) over(order by rn) from ( select code, rn, decode(lag(code) over(order by rn), code, 0, 1) flag from (select code, rownum rn from t) )
-- 정렬 기준항목이 필요한 문제입니다. WITH t AS ( SELECT 1 seq, 'AAA' dept FROM dual UNION ALL SELECT 2, 'AAA' FROM dual UNION ALL SELECT 3, 'AAA' FROM dual UNION ALL SELECT 4, 'AAA' FROM dual UNION ALL SELECT 5, 'BBB' FROM dual UNION ALL SELECT 6, 'BBB' FROM dual UNION ALL SELECT 7, 'AAA' FROM dual UNION ALL SELECT 8, 'AAA' FROM dual UNION ALL SELECT 9, 'BBB' FROM dual ) SELECT seq , dept , SUM(flag) OVER(ORDER BY seq) grp FROM (SELECT seq , dept , DECODE(LAG(dept) OVER(ORDER BY seq), dept, 0, 1) flag FROM t ) ;