Postgresql get first and last day of all iso week in a given year

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

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

i wrote this postgresl script to get the first and last day of all iso week in a given year. It is working perfectly, i just need to know if it can be improved

回答1:

You can use generate_series() to avoid the convoluted CTE and date arithmetics. Here's an example to get you started:

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

You'll want to add a case in the second term to strip out anything in 2017, and it could be rewritten to step a week at a time, but it should get you on the right track.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!