我想创建一个函数来获得正确的一周数.
我已经发布了 here以找到“原生”解决方案,但显然没有.
我已经发布了 here以找到“原生”解决方案,但显然没有.
我试图根据这个mysql example创建功能
CREATE OR REPLACE FUNCTION week_num_year(_date date) RETURNS integer AS $BODY$declare _year integer; begin select date_part('year',_date) into _year; return ceil((to_char(_date,'DDD')::integer+(to_char(('01-01-'||_year)::date,'D')::integer%7-7))/7); end;$BODY$ LANGUAGE plpgsql VOLATILE COST 100;
但它给出了错误的结果,有人可以帮助我吗?
我的配置:Postgresql 9.2
create or replace function week_num_year(_date date) returns integer as $body$ declare _year date; _week_number integer; begin select date_trunc('year',_date)::date into _year ; with first_friday as ( select extract(doy from a::date) ff from generate_series(_year,_year + 6,'1 day') s(a) where extract(dow from a) = 5 ) select floor( (extract(doy from _date) - (select ff from first_friday) - 1) / 7 ) + 2 into _week_number ; return _week_number ; end; $body$ language plpgsql immutable