Postgresql获得给定年份中所有iso周的第一天和最后一天

时间:2013-11-19 21:17:33

标签: sql postgresql

select week_num, week_start, week_end,to_char(week_start,'dd Dy Mon yyyy'), to_char(week_end,'dd Dy Mon yyyy') from(
WITH RECURSIVE t(n) AS (
    select (date_trunc('week',(date_trunc('week',(2016 || '-01-04')::date)::date - interval '1 day')::date))::date
  UNION ALL
    SELECT (n - interval '1 week')::date  FROM t WHERE  extract(WEEK from n ) > 1
)
SELECT n as week_start, (n + interval '6 days')::date as week_end, extract(WEEK from n ) as week_num  
FROM t 
) as weeks order by week_num

我写了这个postgresql脚本来获取给定年份中所有iso周的第一天和最后一天。它工作得很好,我只需要知道它是否可以改进

1 个答案:

答案 0 :(得分:4)

您可以使用generate_series()来避免错综复杂的CTE和日期算术。这是一个让你入门的例子:

select d, d + interval '6 days'
from generate_series('2016-01-01'::date, '2016-12-31'::date, '1 day'::interval) d
where date_trunc('week', d) = d

你需要在第二个学期添加一个案例,以便在2017年删除任何内容,并且可以一次重写一周,但它应该让你走上正确的轨道。