2012-05-16 3 views
1

두 주간에 주간 범위를 생성 할 수있는 솔루션을 찾고 있습니다. 여기서 요일 범위는 요일을 기준으로합니다.
예 :요일을 기준으로 두 날짜 사이의 주간 범위 생성

date1 = 2011-12-17 date2 = 2012-05-16 

결과 : 나는 PostgreSQL을 내 SQL을 작성했습니다

week1 2011-12-17 to 2011-12-17 -- since it the first date false on a saturday 
week2 2011-12-18 to 2011-12-24 
... 
last week 2012-05-13 to 2012-05-16 

:

SELECT 
    time_series.cur 
    ,case (6 - date_part('dow', cur)::int) = 0 
    when true then cur 
     else case time_series.cur + (6 - date_part('dow',cur)::int) < current_date 
      when true then time_series.cur + (6 - date_part('dow', cur)::int) 
      else current_date 
      end 
     end 
    as nxt 
FROM 
    (select generate_series(current_date - 151 
          , current_date, '1 day')::date AS cur) time_series 
where cur < current_date 
and case (current_date - 151 != cur and cur != current_date) 
     when true then date_part('dow', cur)::int = 0 
     else true 
     end 

이 할 수있는 청소기 방법이 있나요?

+0

[이 최근 질문] (http://stackoverflow.com/q/10597101/939860)까지 후속 조치를 취하십시오. –

답변

2

이 조금 청소기를 보인다 (그리고 훨씬 빠르게) :

WITH x AS (
    SELECT '2011-12-17'::date AS my_start 
     , '2012-05-16'::date As my_end 
    ) 
SELECT GREATEST(d1, my_start) AS d1 
     ,LEAST(d1 + 6, my_end) AS d2 
FROM (
    SELECT generate_series(date_trunc('week', my_start + 1) 
         , date_trunc('week', my_end + 1) 
         , '1 week')::date - 1 AS d1 
    FROM x 
    ) d, x 

내가, 내 answer to your previous question에 주 일요일부터 토요일까지 만이 시간을 설명처럼.

+0

감사합니다. Erwin, 이전 질문에서 대답을 발견하지 못했습니다. –

+0

@MikeMontesines : 표준 주에서 근무일 변경시 잘못된 행이 추가되는 경우가 수정되었습니다. 'date_trunc()'앞에 며칠 씩 추가하여 효과를 상쇄하십시오. –