This year 2014 has:
Jan-4
Feb-4
Mar-5
Apr-4
May-4
Jun-5
Jul-4
Aug-4
Sep-5
Oct-4
Nov-4
Dec-5
How to calculate this for any given year?
This year 2014 has:
Jan-4
Feb-4
Mar-5
Apr-4
May-4
Jun-5
Jul-4
Aug-4
Sep-5
Oct-4
Nov-4
Dec-5
How to calculate this for any given year?
There are multiple ways to define "weeks in a month" exactly. Assuming your count is defined (as your numbers indicate):
How many Mondays lie in each month of the year?
You can generate it like that:
Simple:
SELECT EXTRACT(month FROM d) AS mon, COUNT(*) AS weeks
FROM generate_series('2014-01-01'::date
, '2014-12-31'::date
, interval '1 day') d
WHERE EXTRACT(isodow FROM d) = 1 -- only Mondays
GROUP BY 1
ORDER BY 1;
Fast:
SELECT EXTRACT(month FROM d) AS mon, COUNT(*) AS weeks
FROM generate_series ('2014-01-01'::date -- offset to first Monday
+ (8 - EXTRACT(isodow FROM '2014-01-01'::date)::int)%7
, '2014-12-31'::date
, interval '7 days') d
GROUP BY 1
ORDER BY 1;
Either way you get:
mon weeks
1 4
2 4
3 5
4 4
5 4
6 5
7 4
8 4
9 5
10 4
11 4
12 5
Just replace 2014
with the year of interest in each query.
Applying the ISO 8601 to a month as suggested here
select
to_char(d, 'YYYY Mon') as "Month",
case when
extract(dow from d) in (2,3,4)
and
extract(day from (d + interval '1 month')::date - 1) + extract(dow from d) >= 33
then 5
else 4
end as weeks
from generate_series(
'2014-01-01'::date, '2014-12-31', '1 month'
) g (d)
;
Month | weeks
----------+-------
2014 Jan | 5
2014 Feb | 4
2014 Mar | 4
2014 Apr | 4
2014 May | 5
2014 Jun | 4
2014 Jul | 5
2014 Aug | 4
2014 Sep | 4
2014 Oct | 5
2014 Nov | 4
2014 Dec | 4