SQL 사용자 강좌 - SQLER들이 직접 만들어 나가는 강좌 게시판
전에 Q/A와 tip에 있었던 내용인데... 찾을려니 없어서 올려봅니다,.
연속된 일자의 관련되어 자료를 만들때 이런 쿼리를 이용하시면 쉽게 응용할수 있을듯 해서요...
drop table #test
go
select *
into #test
from (
select '20090101' dd union all
select '20090102' dd union all
select '20090105' dd union all
select '20090106' dd union all
select '20090107' dd union all
select '20090110' dd union all
select '20090111' dd union all
select '20090121' dd union all
select '20090201' dd union all
select '20090301' dd union all
select '20090302' dd union all
select '20090305' dd union all
select '20090401' dd union all
select '20090402' dd ) r
select MIN(dd) std_dt, MAX(dd) end_dt , COUNT(*) cnt
from (
select dd
, ROW_NUMBER() over ( order by dd ) idx -- 자료의 일자별 순서를 매긴다.
, DATEDIFF( dd, dd, getdate() ) no -- 오늘날짜 기준으로 일자의 차이값을 계산.
from #test
) r
group by idx + no -- 차이값과 순서값을 더하므로해서 연속된일인지 여부 , 동일한 값일때는 연속된일이 됩니다.
-- 이해가 안가시면 인라인뷰 부분을 별도로 실행해보시면 확인가능.
order by idx + no desc
결과
-----------------------------------------------------------
std_dt end_dt cnt ----------------------------------------------------------- 20090101 20090102 2 20090105 20090107 3 20090110 20090111 2 20090121 20090121 1 20090201 20090201 1 20090301 20090302 2 20090305 20090305 1 20090401 20090402 2



오~ 아주 유용한 팁이죠 ㅎㅎ
잘 보았습니다~^^
(혹시 오늘 오시나요??)