2014年有:
Jan-4
Feb-4
Mar-5
Apr-4
May-4
Jun-5
Jul-4
Aug-4
Sep-5
Oct-4
Nov-4
Dec-5
如何计算任何一年的成本?
有多种方法可以准确定义"一个月中的几周"。假设您的计数已定义(如您的数字所示):
一年中每个月有多少个星期一
你可以这样生成:
简单:
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;
快速:
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;
无论哪种方式,你都会得到:
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
只需将2014
替换为每个查询中感兴趣的年份。
将ISO 8601应用于此处建议的一个月
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