查询计算年周

时间:2016-02-08 10:21:10

标签: postgresql

我需要以这样一种方式帮助查询:在一周中,在一年中有52周

2015年有52周,但2016年的周年应该从201601开始,这是2016年的第一周,而不是2015年第53周的延续。

2015 jan 1--> 201501(1st week of 2015) likewise
2016 jan 1 --> 201601(1st week of 2016) it shouldnt be 201553(53rd week of 2015)

2 个答案:

答案 0 :(得分:1)

试试这个

CREATE OR replace FUNCTION fn_yearofweek (val DATE)
RETURNS TEXT AS $$
SELECT extract(year FROM val)::TEXT || cast(floor((extract(doy FROM val) - 1) / 7) + 1 AS TEXT);
$$
LANGUAGE sql

用法:

SELECT fn_yearofweek('2015-01-01')
      ,fn_yearofweek('2015-12-31')
      ,fn_yearofweek('2016-01-01');

结果:

fn_yearofweek fn_yearofweek    fn_yearofweek 
------------- ---------------- ---------------- 
20151         201553           20161     

答案 1 :(得分:1)

Postgres支持两种类型的"周"计算。 ISO标准(这是您想要的)和一周编号,其中第一周从一年的第一天开始。

这两个可以使用to_char()函数(

)获得
select to_char(date '2016-01-01', 'WW') as week_january, 
       to_char(date '2015-12-31', 'WW') as week_december,
       to_char(date '2016-01-01', 'IW') as iso_week_january, 
       to_char(date '2016-12-31', 'IW') as iso_week_december

以上内容将返回以下内容:

week_january | week_december | iso_week_january | iso_week_december
-------------+---------------+------------------+------------------
01           | 53            | 53               | 52               

如果您需要将其作为实数整数而不是字符串,只需将结果转换为integer,例如:to_char(date '2016-01-01', 'WW')::integer

手册中解释了to_char()的格式:
http://www.postgresql.org/docs/9.5/static/functions-formatting.html#FUNCTIONS-FORMATTING-DATETIME-TABLE

作为旁注:为了使ISO周正常工作,您需要将其与ISO年周结合起来:to_char(date '2016-01-01', 'IYYY')将返回2015