WITH t AS ( SELECT 'M123456789' id, '리차드' nm, '입국' gb, '2015-09-07' dt FROM dual UNION ALL SELECT 'M123456789', '리차드', '출국', '2015-09-11' FROM dual UNION ALL SELECT 'M123456789', '리차드', '입국', '2015-09-23' FROM dual UNION ALL SELECT 'M123456798', '마이클', '입국', '2015-08-30' FROM dual UNION ALL SELECT 'M123456798', '마이클', '출국', '2015-09-02' FROM dual UNION ALL SELECT 'M123456798', '마이클', '입국', '2015-09-12' FROM dual UNION ALL SELECT 'M123456795', 'TST' , '입국', '2015-08-30' FROM dual UNION ALL SELECT 'M123456795', 'TST' , '출국', '2015-08-30' FROM dual ) SELECT id, nm , i_dt, o_dt , TO_DATE(o_dt, 'yyyy-mm-dd') - TO_DATE(i_dt, 'yyyy-mm-dd') + 1 cnt FROM (SELECT id, nm, gb , dt i_dt , LEAD(dt) OVER(PARTITION BY id ORDER BY dt, gb) o_dt FROM t ) WHERE gb = '입국' ;