#title 범위 중복 문제 [[TableOfContents]] 범위 문제가 은근히 골때리면서도 자주 질문이 되는 것이다. 알고보면 개뿔도 아니라는.. ==== 문제 ==== 아래와 같은 데이터 셋이 있다. A intime outtime 1 10:00 12:00 * 1 11:00 14:00 * 1 15:00 16:00 2 13:00 15:00 * 2 12:00 14:00 * 3 08:00 11:00 다음과 같이 범위가 중복되는 건이 몇 건인지 알고 싶다. A count 1 2 2 2 3 0 문제 원본: http://www.sqler.com/350776#1 ==== 해결 ==== 다른 방법도 있을테지만, 쉽고 유지보수가 용이한 쿼리가 좋은 쿼리여~ {{{ ;with temp (a, intime, outtime) as ( select 1, 10, 12 union all select 1, 11, 14 union all select 1, 15, 16 union all select 2, 13, 15 union all select 2, 12, 14 union all select 3, 08, 11 ) select a.a , count(case when b.a is not null then 1 end) cnt from temp a left join temp b on a.intime <= b.outtime and a.outtime >= b.intime and a.a = b.a and a.intime <> b.intime and a.outtime <> b.outtime group by a.a /* 임의의 시간 범위가 있다면.. |------------| 시작 *----------------> <-------------* 종료 이렇게 들어오면 true 다. |------------| 시작 *----------------> <-------------* 종료 이렇게 되면 종료조건은 true이나 시작이 false이므로 2개의 조건을 and하면 false가 된다. */ }}}