根据星期几生成两个日期之间的每周范围

时间:2012-05-16 10:14:28

标签: sql postgresql date-range dayofweek

我正在寻找一个解决方案,我可以在两个日期生成每周范围 每周范围将基于星期几 例如:

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

我在PostgreSQL中编写了我的SQL:

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

有更简洁的方法吗?

1 个答案:

答案 0 :(得分: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中所解释的那样,这一周只有周日到周六。