2013-02-13 35 views
7

我想創建一個函數來獲得正確的一週數。 我已經發布here找到一個'原生'解決方案,但顯然沒有。功能獲得正確的一週數

我tryed是代碼轉換到PostgreSQL來創建基於此mysql example

這裏funcrtion:

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

回答

6
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 
+0

再次感謝@Clodoaldo – Houari 2013-02-13 19:05:43

0

怎麼樣inbuild提取功能?

SELECT extract (week from current_timestamp) FROM A_TABLE_FROM_YOUR_DB; 
+0

不,如果你有,例如測試:從「2005-01 SELECT提取物(周-01':: date)給出53,並且應該給1,因爲這是第一週(考慮到星期六是一週的第一天) – Houari 2013-02-13 15:27:29

+0

@Houari呃,不,它不是。這是去年最後一週的最後一部分。週數很愚蠢,這是它們沒有被廣泛使用的原因之一。查看日曆以瞭解原因。 IIRC有時第二年的第一週也可以在去年的最後幾天開始。 – 2013-02-13 16:05:48

+0

@CraigRinger你爲什麼說這個'笨'?這些都是要求,我想要得到它的解決方案! – Houari 2013-02-13 18:48:32

16

如果你想正確的週數使用:

select extract(week from '2012-01-01'::date); 

會產生這樣的結果52,如果你看看在日曆上是正確的。

現在,如果您確實希望將星期數定義爲「每7天從一年的第一天開始」,那很好,但它與其他人使用的星期數不匹配,並且有一些奇怪的怪癖:

select floor((extract(doy from '2011-01-01'::date)-1)/7)+1; 

順便說一句,解析日期字符串,並用字符串函數篡改它們幾乎總是一個非常糟糕的主意。

0

您可以通過運行檢索一週,也是今年的星期幾:

select id,extract(DOW from test_date),extract(week from test_date), testdate,name from yourtable