안녕하세요. 쿼리 질문이 있어 올립니다.
아래와 같이 테이블이 있고 register_date를 올림으로 정렬해서 나타내고 있으며 duration은
정렬 된 register_date의 다음 열의 값과 시간 차이 입니다. 여기서 type의 값이 off가 이후에 나오는 열의 duration 은 모두 0을 가져야 되며 on 이후의 값은 정상적은 duration 을 가져야 됩니다. 이걸 어떻게 처리 할 수 있을까요? 알려주시면 감사하겠습니다.
REGISTER_DATE | TYPE | DURATION |
2019/08/01 00:31:24 | 1 | |
2019/08/01 00:31:25 | off | 0 |
2019/08/01 00:33:36 | 0 | |
2019/08/01 00:34:36 | 0 | |
2019/08/01 00:37:36 | on | 0 |
2019/08/01 00:37:36 | 2 | |
2019/08/01 00:37:38 | 1 | |
2019/08/01 00:37:39 | off | 0 |
2019/08/01 00:37:39 | ||
2019/08/01 00:42:55 | on | 0 |
2019/08/01 00:42:55 | 16 | |
2019/08/01 00:43:11 | 8 | |
2019/08/01 00:43:19 | off | 1 |
2019/08/01 00:43:20 | on | 0 |
2019/08/01 00:43:25 | 5 | |
2019/08/01 00:43:27 | 2 |
with t(reg_dt, typ) as ( select to_date('2019/08/01 00:31:24', 'yyyy/mm/dd hh24:mi:ss'), null from dual union all select to_date('2019/08/01 00:31:25', 'yyyy/mm/dd hh24:mi:ss'), 'off' from dual union all select to_date('2019/08/01 00:33:36', 'yyyy/mm/dd hh24:mi:ss'), null from dual union all select to_date('2019/08/01 00:34:36', 'yyyy/mm/dd hh24:mi:ss'), null from dual union all select to_date('2019/08/01 00:37:36', 'yyyy/mm/dd hh24:mi:ss'), 'on' from dual union all select to_date('2019/08/01 00:37:36', 'yyyy/mm/dd hh24:mi:ss'), null from dual union all select to_date('2019/08/01 00:37:38', 'yyyy/mm/dd hh24:mi:ss'), null from dual union all select to_date('2019/08/01 00:37:39', 'yyyy/mm/dd hh24:mi:ss'), 'off' from dual union all select to_date('2019/08/01 00:37:39', 'yyyy/mm/dd hh24:mi:ss'), null from dual union all select to_date('2019/08/01 00:42:55', 'yyyy/mm/dd hh24:mi:ss'), 'on' from dual union all select to_date('2019/08/01 00:42:55', 'yyyy/mm/dd hh24:mi:ss'), null from dual union all select to_date('2019/08/01 00:43:11', 'yyyy/mm/dd hh24:mi:ss'), null from dual ) select reg_dt , typ , decode(vtyp, 'on', diff_dt, 0) as duration from (select reg_dt , typ , round((lead(reg_dt) over(order by reg_dt) - reg_dt)*(24*60*60)) as diff_dt , coalesce(typ, lag(typ) ignore nulls over(order by reg_dt), 'on') vtyp from t order by reg_dt ) ;
초까지 동일한 자료가 존재하네요?
예시엔 on 끼리 중복, off 끼리 중복되긴 한지만.
on/off 가 함께 시간이 중복되면 정렬이 애매해 집니다.
같은 시간에 on 2개, off 2개 총 4개가 중복되었을 때?
정렬을 어찌 해야 할 지 불명확해 집니다.
(on on off off) 가 될 수 도 있고
(on off off on) 가 될 수 도 있고
또 다른 순서로 될수가 있는데.. 순서에 따라 결과가 달라지게 됩니다.
그리고, 질문에 DBMS 가 명시되어 있지 않네요.
또한, 예시 자료가 일관성이 없네요.
처음에는 다음 시간과의 차이가 나오다가 마지막에는 이전시간과의 차이가 나오네요.