2012-05-16 36 views
1

我正在尋找一種解決方案,我可以在兩個日期生成每週範圍 ,其中每週範圍將基於星期幾。
例子:根據星期幾生成兩個日期之間的每週範圍

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

結果:

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 

我寫我的SQL在PostgreSQL中:

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()'之前加上相應數量的天來抵消效果。 –

相關問題